如果我救下面的脚本为“args.bash”和运行bash args.bash -a 'foo bar'
#!/bin/bash
main() {
set -x
which "[email protected]"
local args="[email protected]"
which "$args"
which $args
local args=$(printf " %q" "[email protected]")
which "$args"
which $args
}
main "[email protected]"
我很惊讶地看到,这些打印不同的结果。第一个打印:
which -a 'foo bar'
我期望!它将正确的参数分组。
他们其余的打印,依次是:
which '-a foo bar'
which -a foo bar
which ' -a foo\ bar'
which -a 'foo\' bar
这都是不正确的或多或少。我如何将"[email protected]"
分配给一个变量,并让它回显与第一个命令相同的输出?
你不能在字符串中存储任意的命令/参数,并保持正确的引号/等。参见[Bash FAQ 050](http://mywiki.wooledge.org/BashFAQ/050)讨论这个问题。你需要使用一个数组。 –
好吧 - 他正在使用'printf%q',它改变了一些东西,但是一个数组仍然是正确的。 –
'printf%q'是我知道的唯一尝试 - 打开任何其他建议。 –