【发布时间】:2015-10-07 23:35:55
【问题描述】:
我在 bash 脚本中有一些变量,这些变量可能包含文件名或未设置。它们的内容应该作为附加参数传递给程序。但是,当变量未设置时,这会留下一个空参数。
$ afile=/dev/null
$ anotherfile=/dev/null
$ unset empty
$ cat "$afile" "$empty" "$anotherfile"
cat: : No such file or directory
没有引号,它工作得很好,因为附加参数被简单地省略了。但由于变量可能包含空格,因此必须在此处引用。
我知道我可以简单地将整行包含在空性测试中。
if [ -z "$empty" ]; then
cat "$afile" "$anotherfile"
else
cat "$afile" "$empty" "$anotherfile"
fi
但是对每个变量进行一次测试会产生一个庞大而复杂的决策树。
有没有更紧凑的解决方案? bash 可以省略带引号的空变量吗?
【问题讨论】:
标签: bash arguments argument-passing variable-expansion