喜欢将bash脚本中的所有命令行参数存储到单个变量中

Mar*_*iek 13 unix linux bash shell command-line-interface

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

我想这样称呼它

foo.sh Here is a bunch of stuff on the command-line
Run Code Online (Sandbox Code Playgroud)

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

所以我的输出是:

Here is a bunch of stuff on the command-line
Run Code Online (Sandbox Code Playgroud)

我该怎么做?

Dav*_*d Z 27

echo "$*"
Run Code Online (Sandbox Code Playgroud)

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

thevar="$*"
Run Code Online (Sandbox Code Playgroud)

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


Pau*_*ce. 27

如果你想避免涉及$ 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
Run Code Online (Sandbox Code Playgroud)

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
Run Code Online (Sandbox Code Playgroud)

注意,如果在分配$ splatvar之后进行$ IFS的赋值,那么所有输出都是相同的($ IFS在"atsplat2"示例中没有效果).