Bash 将变量作为带引号的参数传递
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/39583838/
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
Bash pass variable as argument with quotes
提问by user2249516
Assume ./program
is a program that just prints out the parameters;
假设./program
是一个只打印参数的程序;
$ ./program "Hello there"
Hello there
How can I properly pass arguments with quotes in from a variable? I am trying to do this;
如何从变量中正确传递带引号的参数?我正在尝试这样做;
$ args='"Hello there"'
$ echo ${args}
"Hello there"
$ ./program ${args}
Hello there # This is 1 argument
but instead, when I go through a variable the quotes in args
seem to be ignored so I get;
但是相反,当我通过一个变量时,引号中的引号args
似乎被忽略了,所以我得到了;
$ args='"Hello there"'
$ echo ${args}
"Hello there"
$ ./program ${args}
"Hello there" # This is 2 arguments
Is it possible to have bash treat the quotes as if I entered them myself in the first code block?
是否可以让 bash 将引号视为我自己在第一个代码块中输入?
采纳答案by redneb
I don't know where you got program
from, but it appears that it's broken. Here's a correct way to write it in bash:
我不知道你program
从哪里得到的,但它似乎坏了。这是在 bash 中编写它的正确方法:
#!/bin/bash
for arg in "$@"; do
echo "$arg"
done
This will print each argument in a separate line to make them easier to distinguish (it will of course have a problem with arguments that contain a line break, but we will not pass such an argument).
这将在单独的行中打印每个参数,使它们更容易区分(当然,包含换行符的参数会有问题,但我们不会传递这样的参数)。
After you have saved the above as program
and gave it the execute permission, try this:
将上述内容另存为program
并授予执行权限后,请尝试以下操作:
$ args='"Hello there"'
$ ./program "${args}"
"Hello there"
whereas
然而
$ args='"Hello there"'
$ ./program ${args}
"Hello
there"