将带有空格的字符串作为参数传递给Bash函数

时间:2010-10-27 07:53:27

标签: bash

给出以下字符串变量

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"

1 个答案:

答案 0 :(得分:2)

Bash很聪明,双引号对匹配$( ... )结构的内部或外部。

因此,echo "$(testfn "foo bar")"有效,testfn函数的结果只会被视为echo内部命令的单个参数。