如果我救下面的腳本爲「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'是我知道的唯一嘗試 - 打開任何其他建議。 –