如何将空变量传递给bash函数并将其实际计为参数?
以下是一个例子:
#/bin/bash
foo(){
echo "foo() called with $# arguments.";
}
BAR=""
foo $BAR
BAR="fubar"
foo $BAR
这个输出是:
foo() called with 0 arguments.
foo() called with 1 arguments.
我希望这两个案例都是foo() called with 1 argument
。
答案 0 :(得分:5)
简单地引用一下这个论点:
BAR=""
foo "$BAR"
BAR="fubar"
foo "$BAR"
输出:
foo() called with 1 arguments.
foo() called with 1 arguments.
双引号变量是shell编程的最佳实践,因为它可以防止空格和特殊(例如*
)字符出现问题。你不能引用它的唯一情况是你真的希望Bash分词变量的内容或扩展通配符:
BAR="a b c"
foo "$BAR"
foo $BAR
BAR="*"
echo "$BAR"
echo $BAR
输出:
foo() called with 1 arguments.
foo() called with 3 arguments.
*
test.sh
答案 1 :(得分:0)
引用BAR:
foo "$BAR"
这会将空字符串发送到foo。