How to store curly brackets in a Bash variable

痞子三分冷 提交于 2019-11-27 07:15:47

问题


I am trying to write a bash script. I am not sure why in my script:

ls {*.xml,*.txt} 

works okay, but

name="{*.xml,*.txt}"
ls $name

doesn't work. I get

ls: cannot access {*.xml,*.txt}: No such file or directory

回答1:


The expression

ls {*.xml,*.txt}

results in Brace expansion and shell passes the expansion (if any) to ls as arguments. Setting shopt -s nullglob makes this expression evaluate to nothing when there are no matching files.

Double quoting the string suppresses the expansion and shell stores the literal contents in your variable name (not sure if that is what you wanted). When you invoke ls with $name as the argument, shell does the variable expansion but no brace expansion is done.

As @Cyrus has mentioned, eval ls $name will force brace expansion and you get the same result as that of ls {\*.xml,\*.txt}.




回答2:


The reason your expansion doesn't work is that brace expansion is performed before variable expansion, see Shell expansions in the manual.

I'm not sure what it is you're trying to do, but if you want to store a list of file names, use an array:

files=( {*.txt,*.xml} )           # these two are the same
files=(*.txt *.xml)
ls -l "${files[@]}"               # give them to a command
for file in "${files[@]}" ; do    # or loop over them
    dosomething "$file"
done

"${array[@]}" expands to all elements of the array, as separate words. (remember the quotes!)



来源:https://stackoverflow.com/questions/43751540/how-to-store-curly-brackets-in-a-bash-variable

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