Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

pass arguments between shell scripts but retain quotes

How do I pass all the arguments of one shell script into another? I have tried $*, but as I expected, that does not work if you have quoted arguments.

Example:

$ cat script1.sh  #! /bin/sh ./script2.sh $*  $ cat script2.sh  #! /bin/sh echo $1 echo $2 echo $3  $ script1.sh apple "pear orange" banana apple pear orange 

I want it to print out:

apple pear orange banana 
like image 597
dogbane Avatar asked Dec 31 '09 21:12

dogbane


People also ask

What is $@ and $* in shell script?

"$@" Stores all the arguments that were entered on the command line, individually quoted ("$1" "$2" ...). So basically, $# is a number of arguments given when your script was executed. $* is a string containing all arguments. For example, $1 is the first argument and so on.

What is $@ in bash?

bash [filename] runs the commands saved in a file. $@ refers to all of a shell script's command-line arguments. $1 , $2 , etc., refer to the first command-line argument, the second command-line argument, etc. Place variables in quotes if the values might have spaces in them.

What is the difference between $@ and $* in bash?

There is no difference if you do not put $* or $@ in quotes. But if you put them inside quotes (which you should, as a general good practice), then $@ will pass your parameters as separate parameters, whereas $* will just pass all params as a single parameter.


1 Answers

Use "$@" instead of $* to preserve the quotes:

./script2.sh "$@" 

More info:

http://tldp.org/LDP/abs/html/internalvariables.html

$*
All of the positional parameters, seen as a single word

Note: "$*" must be quoted.

$@
Same as $*, but each parameter is a quoted string, that is, the parameters are passed on intact, without interpretation or expansion. This means, among other things, that each parameter in the argument list is seen as a separate word.

Note: Of course, "$@" should be quoted.

like image 142
ZoogieZork Avatar answered Sep 22 '22 06:09

ZoogieZork