如何将带引号的参数从变量传递到bash脚本 [英] How to pass quoted arguments from variable to bash script
问题描述
我尝试在变量中构建一组参数,并将其传递给脚本,但是行为与预期不同.
I tried building a set of arguments in a variable and passing that to a script but the behavior different from what I expected.
test.sh
#!/bin/bash
for var in "$@"; do
echo "$var"
done
输入
usr@host$ ARGS="-a \"arg one\" -b \"arg two\""
usr@host$ ./test.sh $ARGS
输出
-a
"arg
one"
-b
"arg
two"
预期
-a
arg one
-b
arg two
请注意,如果将带引号的参数直接传递给脚本,它将起作用.我也可以使用eval解决此问题,但我想了解为什么第一种方法失败了.
Note if you pass the quoted arguments directly to the script it works. I also can work around this with eval but I wanted to understand why the first approach failed.
解决方法
ARGS="./test.sh -a "arg one" -b "arg two""
eval $ARGS
推荐答案
您应该使用一个数组,从某种意义上讲,它提供了第二级引用:
You should use an array, which in some sense provides a 2nd level of quoting:
ARGS=(-a "arg one" -b "arg two")
./test.sh "${ARGS[@]}"
数组扩展会为数组的每个元素产生一个单词,因此在构造要传递给test.sh
的参数列表时,创建数组时引用的空格不会被视为单词分隔符.
The array expansion produces one word per element of the array, so that the whitespace you quoted when the array was created is not treated as a word separator when constructing the list of arguments that are passed to test.sh
.
请注意,POSIX shell不支持数组,但这正是POSIX shell中引入数组的确切缺点.
Note that arrays are not supported by the POSIX shell, but this is the precise shortcoming in the POSIX shell that arrays were introduced to correct.
这篇关于如何将带引号的参数从变量传递到bash脚本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!