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

瘦欲@ 提交于 2019-12-10 12:33:06

问题


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

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?


回答1:


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). 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...




回答2:


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

$ 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.

$ 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).




回答3:


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

echo "$*"

This should do what you want.

More info here.



来源:https://stackoverflow.com/questions/841670/i-would-like-to-store-all-command-line-arguments-to-a-bash-script-into-a-single

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!