我想将 Bash 脚本的所有命令行参数存储到一个变量中

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

I would like to store all command-line arguments to a Bash script into a single variable

linuxbashshellunixcommand-line-interface

提问by Mark Biek

Let's say I have a Bash script called foo.sh.

假设我有一个名为foo.sh的 Bash 脚本。

I'd like to call it like this:

我想这样称呼它:

foo.sh Here is a bunch of stuff on the command-line

And I'd like it to store all of that text into a single variable and print it out.

我希望它将所有文本存储到一个变量中并打印出来。

So my output would be:

所以我的输出是:

Here is a bunch of stuff on the command-line

How would I do this?

我该怎么做?

回答by David Z

echo "$*"

would do what you want, namely printing out the entire command-line arguments, separated by a space (or, technically, whatever the value of $IFSis). If you wanted to store it into a variable, you could do

会做你想做的,即打印出整个命令行参数,用空格分隔(或者,从技术上讲,无论值$IFS是多少)。如果你想把它存储到一个变量中,你可以这样做

thevar="$*"

If that doesn't answer your question well enough, I'm not sure what else to say...

如果这还不能很好地回答你的问题,我不知道还能说什么......

回答by Paused until further notice.

If you want to avoid having $IFS involved, use $@ (or don't enclose $* in quotes)

如果您想避免涉及 $IFS,请使用 $@(或不要将 $* 括在引号中)

$ cat atsplat
IFS="_"
echo "     at: $@"
echo "  splat: $*"
echo "noquote: "$*

$ ./atsplat this is a test
     at: this is a test
  splat: this_is_a_test
noquote: this is a test

The IFS behavior follows variable assignments, too.

IFS 行为也遵循变量赋值。

$ cat atsplat2
IFS="_"
atvar=$@
splatvar=$*
echo "     at: $atvar"
echo "  splat: $splatvar"
echo "noquote: "$splatvar

$ ./atsplat2 this is a test
     at: this is a test
  splat: this_is_a_test
noquote: this is a test

Note that if the assignment to $IFS were made after the assignment of $splatvar, then all the outputs would be the same ($IFS would have no effect in the "atsplat2" example).

请注意,如果在分配 $splatvar 之后对 $IFS 进行分配,则所有输出都将相同($IFS 在“atsplat2”示例中无效)。

回答by Ayman Hourieh

Have a look at the $*variable. It combines all command line arguments into one.

看看$*变量。它将所有命令行参数合二为一。

echo "$*"

This should do what you want.

这应该做你想做的。

More info here.

更多信息在这里。