省略传递空的带引号的参数

XZS*_*XZS 9 bash arguments argument-passing variable-expansion

我的 bash 脚本中有一些变量可能包含文件名或未设置。它们的内容应作为附加参数传递给程序。但是当变量未设置时,这会留下一个空参数。

$ afile=/dev/null
$ anotherfile=/dev/null
$ unset empty
$ cat "$afile" "$empty" "$anotherfile"
cat: : No such file or directory
Run Code Online (Sandbox Code Playgroud)

如果没有引号,它就可以正常工作,因为附加参数被简单地省略了。但由于变量可能包含空格,因此必须在此处用引号引起来。

我知道我可以简单地将整条线包装在对空性的测试中。

if [ -z "$empty" ]; then
  cat "$afile" "$anotherfile"
else
  cat "$afile" "$empty" "$anotherfile"
fi
Run Code Online (Sandbox Code Playgroud)

但对每个变量进行一次测试会产生一棵巨大而复杂的决策树。

有没有更紧凑的解决方案?bash 可以省略带引号的空变量吗?

Gor*_*son 11

您可以使用备用值参数扩展( ${var+altvalue}) 来包含带引号的变量(如果已设置):

cat ${afile+"$afile"} ${empty+"$empty"} ${anotherfile+"$anotherfile"}
Run Code Online (Sandbox Code Playgroud)

由于双引号位于备用值字符串中(而不是整个参数表达式周围),因此它们仅在设置变量时才生效。请注意,您可以使用+(如果设置了变量,则使用替代值)或:+(如果设置了变量且不为空,则使用替代值)。