【发布时间】:2015-08-28 17:41:25
【问题描述】:
如果我将以下脚本保存为 'args.bash' 并运行 bash args.bash -a 'foo bar'
#!/bin/bash
main() {
set -x
which "$@"
local args="$@"
which "$args"
which $args
local args=$(printf " %q" "$@")
which "$args"
which $args
}
main "$@"
看到这些打印出不同的结果,我感到很惊讶。第一个打印:
which -a 'foo bar'
我所期待的!它正确地对参数进行分组。
其余的按顺序打印:
which '-a foo bar'
which -a foo bar
which ' -a foo\ bar'
which -a 'foo\' bar
这在某种程度上都是不正确的。如何将"$@" 分配给变量,并让它回显与第一个命令相同的输出?
【问题讨论】:
-
您不能在字符串中存储任意命令/参数并保持正确的引用/等。有关此问题的讨论,请参阅 Bash FAQ 050。你需要使用一个数组。
-
嗯——他正在使用
printf %q,这有点改变,但数组仍然是正确的。 -
printf %q是我唯一知道要尝试的东西 - 愿意接受任何其他建议。 -
$@具有特殊的行为,正是因为普通参数不能在单个字符串中保持不同的参数(并且数组不在 POSIX 中,而$@是) .
标签: bash escaping arguments printf