如何将字符串参数传递给 bash 脚本中的命令?

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

How to pass a string argument to a command in a bash script?

bashshellargumentsargvquote

提问by qiuxiafei

I concat all the arguments in a variable $ARGS and pass all of them to a command onece togather, just like what the ./test_arg.shdo.

我将所有参数连接到一个变量 $ARGS 中,并将它们全部传递给一个命令 onece togather,就像./test_arg.sh所做的那样。

But i found that the arguments with quoted string was splitted into multiple ones.

但我发现带引号字符串的参数被拆分为多个。

Here is my test scripts, test_arg.shperform the test case and arg.shjust print every argument on seperated line.

这是我的测试脚本,test_arg.sh执行测试用例,arg.sh只是在单独的行上打印每个参数。

$ cat ./test_arg.sh 
#!/bin/sh

ARGS="$ARGS OPT_1"
ARGS="$ARGS OPT_2"
ARGS="$ARGS 'OPT_3 is a string with space'"

echo "./arg.sh $ARGS"

echo '----------------------------'

./arg.sh $ARGS
[ xiafei@xiafeitekiMacBook-Pro ~/tmp ]
$ cat ./arg.sh 
#!/bin/sh

for var in "$@"
do
    echo "arg -> $var"
done

Here coms the result:

结果如下:

$ ./test_arg.sh
./arg.sh  OPT_1 OPT_2 'OPT_3 is a string with space'
----------------------------
arg -> OPT_1
arg -> OPT_2
arg -> 'OPT_3
arg -> is
arg -> a
arg -> string
arg -> with
arg -> space'

But if I put argument directly after the command it works correctly:

但是,如果我在命令之后直接放置参数,它可以正常工作:

$ cat test_arg.sh 
#!/bin/sh
./arg.sh OPT_1 OPT_2 'OPT_3 is a string with space'

[ xiafei@xiafeitekiMacBook-Pro ~/tmp ]
$ sh test_arg.sh 
arg -> OPT_1
arg -> OPT_2
arg -> OPT_3 is a string with space

I guess the problem is the way bash process quotes. Anyone knows about it?

我想问题是 bash 进程引用的方式。有人知道吗?

回答by Lars Brinkhoff

The way the unix shell works, your call to ./arg.sh $ARGSwill not evalutate the ' quotes.

unix shell 的工作方式,您的调用./arg.sh $ARGS不会评估 ' 引号。

One possible solution is to use eval "./arg.sh $ARGS".

一种可能的解决方案是使用eval "./arg.sh $ARGS".