如何将字符串作为 bash 脚本的命令行参数传递?

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

How to pass a string as command line argument for bash script?

bash

提问by sivakumarspnv

I want to pass a string as command line argument to a bash script; Simply my bash script is:

我想将字符串作为命令行参数传递给 bash 脚本;简单地说,我的 bash 脚本是:

>cat test_script.sh

for i in $*
do 
echo $i
done

I typed

我打字

bash test_script.sh test1 test2 "test3 test4"

bash test_script.sh test1 test2 "test3 test4"

Output :

输出 :

test1
test2
test3
test4

Output I am expecting:

我期待的输出:

test1
test2
test3 test4

I tried with backslashes (test1 test2 "test3\ test4") and single quotes but I haven't got the expected result.

我尝试使用反斜杠(test1 test2 "test3\ test4")和单引号,但没有得到预期的结果。

How do I get the expected output?

我如何获得预期的输出?

回答by Jonathan Leffler

You need to use:

您需要使用:

for i in "$@"
do echo $i
done

or even:

甚至:

for i in "$@"
do echo "$i"
done

The first would lose multiple spaces within an argument (but would keep the words of an argument together). The second preserves the spaces in the arguments.

第一个会在参数中丢失多个空格(但会将参数的单词保持在一起)。第二个保留参数中的空格。

You can also omit the in "$@"clause; it is implied if you write for i(but personally, I never use the shorthand).

你也可以省略in "$@"子句;如果你写for i(但就我个人而言,我从不使用速记),这是暗示的。

回答by Danny Hong

Try use printf

尝试使用 printf

for i in $* do $(printf '%q' $i) done