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

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

Bash pass variable as argument with quotes

linuxbash

提问by user2249516

Assume ./programis 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 argsseem 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 programfrom, 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 programand gave it the execute permission, try this:

将上述内容另存为program并授予执行权限后,请尝试以下操作:

$ args='"Hello there"'
$ ./program "${args}"
"Hello there"

whereas

然而

$ args='"Hello there"'
$ ./program ${args}
"Hello
there"