How can I do brace expansion on variables? [duplicate]

感情迁移 提交于 2019-11-28 12:58:11

See man bash:

The order of expansions is: brace expansion, tilde expansion, parameter, variable and arithmetic expansion and command substitution (done in a left-to-right fashion), word splitting, and pathname expansion.

As you see, variable expansion happens later than brace expansion.

Fortunately, you don't need it at all: let the user specify the braced paths, let the shell expand them. You can then just

mv "$@"

If you need to separate the arguments, use an array and parameter expansion:

sources=("${@:1:$#-1}")
target=${@: -1}
mv "${sources[@]}" "$target"

This is a way:

ex=({foo,bar,baz})
echo ${ex[@]}
foo bar baz

Brace expansion does not work the way you are attempting to use it. Brace expansion is basically used to generate lists to be applied within the context of the present command. You have two primary modes where brace expansion is used directly (and many more where brace expansion is used a part of another operator.) The two direct uses are to expand a list of items within a comma-separated pair of braces. e.g.

$ touch file_{a,b,c,d}.txt

After executing the command, brace expansion creates all four files with properly formatted file names in the present directory:

$ ls -1 file*.txt
file_a.txt
file_b.txt
file_c.txt
file_d.txt

You may also use brace-expansion in a similar manner to generate lists for loop iteration (or wherever a generated system/range of numbers in needed). The syntax for using brace expansion here is similar, but with .. delimiters within the braces (instead of ',' separation). The syntax is {begin..end..increment} (whereincrement can be both positive and negative) e.g.

$ for i in {20..-20..-4}; do echo $i; done)
20
16
12
8
4
0
-4
-8
-12
-16
-20

(note: using variables for begin, end or increment is not allowed without some horrible eval trickery -- avoid it.).

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!