给出以下字符串变量
VAR="foo bar"
我需要将它传递给bash函数,并像往常一样通过$1
访问它。到目前为止,我还没弄清楚如何做到这一点:
#!/bin/bash
function testfn(){
echo "in function: $1"
}
VAR="foo bar"
echo "desired output is:"
echo "$(testfn 'foo bar')"
echo "Now, what about a version with \$VAR?"
echo "Note, by the way, that the following doesn't do the right thing:"
echo $(testfn "foo bar") #prints: "in function: foo bar"
答案 0 :(得分:2)
Bash很聪明,双引号对匹配$( ... )
结构的内部或外部。
因此,echo "$(testfn "foo bar")"
有效,testfn
函数的结果只会被视为echo
内部命令的单个参数。