Bash 将变量作为带有引号的参数传递

use*_*516 5 linux bash

假设./program是一个只打印出参数的程序;

$ ./program "Hello there"
Hello there
Run Code Online (Sandbox Code Playgroud)

如何正确地从变量中传递带有引号的参数?我正在努力做到这一点;

$ args='"Hello there"'  
$ echo ${args}  
"Hello there"  
$ ./program ${args}  
Hello there # This is 1 argument
Run Code Online (Sandbox Code Playgroud)

但相反,当我遍历一个变量时,引号中的引号args似乎被忽略,所以我得到;

$ args='"Hello there"'
$ echo ${args}
"Hello there"
$ ./program ${args}
"Hello there" # This is 2 arguments
Run Code Online (Sandbox Code Playgroud)

是否可以让 bash 将引号视为我自己在第一个代码块中输入的引号?

red*_*neb 3

我不知道你从哪里来的program,但看起来它已经坏了。下面是在 bash 中正确的写法:

#!/bin/bash

for arg in "$@"; do
    echo "$arg"
done
Run Code Online (Sandbox Code Playgroud)

这会将每个参数打印在单独的行中,以使它们更容易区分(当然,包含换行符的参数会出现问题,但我们不会传递这样的参数)。

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

$ args='"Hello there"'
$ ./program "${args}"
"Hello there"
Run Code Online (Sandbox Code Playgroud)

然而

$ args='"Hello there"'
$ ./program ${args}
"Hello
there"
Run Code Online (Sandbox Code Playgroud)

  • @user2249516在这种情况下,最简单的解决方案可能是使用 `xargs`: `echo "$args" | xargs ./program`。或者使用 `eval`: `eval './program "$args"'`。 (3认同)