我正在尝试编写一个 bash 脚本。我不确定为什么在我的脚本中:
ls {*.xml,*.txt}
工作正常,但是
name="{*.xml,*.txt}"
ls $name
不起作用。我明白了
ls: cannot access {*.xml,*.txt}: No such file or directory
我正在尝试编写一个 bash 脚本。我不确定为什么在我的脚本中:
ls {*.xml,*.txt}
工作正常,但是
name="{*.xml,*.txt}"
ls $name
不起作用。我明白了
ls: cannot access {*.xml,*.txt}: No such file or directory
表达方式
ls {*.xml,*.txt}
导致Brace 扩展和 shell 将扩展(如果有)ls
作为参数传递。shopt -s nullglob
当没有匹配的文件时,设置使该表达式的值为空。
双引号字符串会抑制扩展,并且 shell 将文字内容存储在变量中name
(不确定这是否是您想要的)。当您调用ls
with$name
作为参数时,shell 会进行变量扩展,但不会进行大括号扩展。
正如@Cyrus 所提到的,eval ls $name
将强制大括号扩展,您会得到与ls {\*.xml,\*.txt}
.
您的扩展不起作用的原因是大括号扩展是在变量扩展之前执行的,请参阅手册中的Shell 扩展。
我不确定您要做什么,但是如果您想存储文件名列表,请使用数组:
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[@]}"
扩展为数组的所有元素,作为单独的单词。(记住引号!)