简体   繁体   English

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

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

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? 我该怎么做?

echo "$*"

would do what you want, namely printing out the entire command-line arguments, separated by a space (or, technically, whatever the value of $IFS is). 将执行您想要的操作,即打印出整个命令行参数,并以空格分隔(或者,从技术上讲,无论$IFS的值如何)。 If you wanted to store it into a variable, you could do 如果要将其存储到变量中,则可以执行

thevar="$*"

If that doesn't answer your question well enough, I'm not sure what else to say... 如果那还不能很好地回答您的问题,我不确定还有什么要说的。。。

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”示例中无效)。

Have a look at the $* variable. 看一下$*变量。 It combines all command line arguments into one. 它将所有命令行参数组合为一个。

echo "$*"

This should do what you want. 这应该做您想要的。

More info here. 更多信息在这里。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM