将带有空格的字符串作为参数传递给 Bash 函数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4031007/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Pass a string with spaces as an argument to Bash function
提问by Leo Alekseyev
Given the following string variable
给定以下字符串变量
VAR="foo bar"
I need it to be passed to a bash function, and accesses it, as usual, via $1. So far I haven't been able to figure out how to do it:
我需要将它传递给 bash 函数,并像往常一样通过$1. 到目前为止,我一直无法弄清楚如何做到这一点:
#!/bin/bash
function testfn(){
echo "in function: "
}
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"
回答by Benoit
Bash is smart and pairs of double quotes match either inside or outside of a $( ... )structure.
Bash 很聪明,双引号对匹配在$( ... )结构内部或外部。
Hence, echo "$(testfn "foo bar")"is valid, and the result of your testfnfunction will only be considered as a single argument to the echointernal command.
因此,echo "$(testfn "foo bar")"是有效的,并且您的testfn函数的结果将仅被视为echo内部命令的单个参数。

