Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

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?

like image 514
Mark Biek Avatar asked May 08 '09 20:05

Mark Biek


People also ask

How do you assign a all the arguments to a single variable?

Assigning the arguments to a regular variable (as in args="$@" ) mashes all the arguments together like "$*" does. If you want to store the arguments in a variable, use an array with args=("$@") (the parentheses make it an array), and then reference them as e.g. "${args[0]}" etc.

How do I get command line arguments in bash?

You can handle command-line arguments in a bash script in two ways. One is by using argument variables, and another is by using the getopts function.

Which shell script code will create files for all command line arguments?

$@ is basically use for refers all the command-line arguments of shell-script. $1 , $2 , $3 refer to the first command-line argument, the second command-line argument, third argument.


2 Answers

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

like image 125
Dennis Williamson Avatar answered Oct 23 '22 02:10

Dennis Williamson


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

like image 32
David Z Avatar answered Oct 23 '22 04:10

David Z