In shell scripts, what is the difference between $@
and $*
?
Which one is the preferred way to get the script arguments?
Are there differences between the different shell interpreters about this?
The difference between "$*" and $* is that the quotes keep the expansion of $* as a single string while having no quotes allows the parts of $* to be treated as individual items. This is the general meaning of double quotes; the behaviour is not specific to $* and $@.
$@ 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.
The $@ holds list of all arguments passed to the script. The $* holds list of all arguments passed to the script.
If the $0 special variable is used within a Bash script, it can be used to print its name and if it is used directly within the terminal, it can be used to display the name of the current shell.
From here:
$@ behaves like $* except that when quoted the arguments are broken up properly if there are spaces in them.
Take this script for example (taken from the linked answer):
for var in "$@" do echo "$var" done
Gives this:
$ sh test.sh 1 2 '3 4' 1 2 3 4
Now change "$@"
to $*
:
for var in $* do echo "$var" done
And you get this:
$ sh test.sh 1 2 '3 4' 1 2 3 4
(Answer found by using Google)
A key difference from my POV is that "$@" preserves the original number of arguments. It's the only form that does. For that reason it is very handy for passing args around with the script.
For example, if file my_script contains:
#!/bin/bash main() { echo 'MAIN sees ' $# ' args' } main $* main $@ main "$*" main "$@" ### end ###
and I run it like this:
my_script 'a b c' d e
I will get this output:
MAIN sees 5 args
MAIN sees 5 args
MAIN sees 1 args
MAIN sees 3 args
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With