如何将带引号的参数从变量传递给 bash 脚本

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19012991/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 08:03:31  来源:igfitidea点击:

How to pass quoted arguments from variable to bash script

bashescapingcommand-line-argumentsquotes

提问by dcompiled

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

input

输入

usr@host$ ARGS="-a \"arg one\" -b \"arg two\""
usr@host$ ./test.sh $ARGS

output

输出

-a
"arg
one"
-b
"arg
two"

expected

预期的

-a
arg one
-b
arg two

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.

请注意,如果您将带引号的参数直接传递给它可以工作的脚本。我也可以用 eval 解决这个问题,但我想了解为什么第一种方法失败。

workaround

解决方法

ARGS="./test.sh -a "arg one" -b "arg two""
eval $ARGS

回答by chepner

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[@]}"

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.

数组扩展为数组的每个元素生成一个单词,因此在构造传递给 的参数列表时,创建数组时引用的空格不会被视为单词分隔符test.sh

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.

请注意,POSIX shell 不支持数组,但这是 POSIX shell 中引入数组以纠正的确切缺点。