Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between $@ and $* in shell scripts?

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?

like image 635
nicoulaj Avatar asked May 03 '10 22:05

nicoulaj


People also ask

What is the difference between the $@ and $* variables in Bash?

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

What does $@ mean in shell script?

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

How $@ and $* is different in Unix?

The $@ holds list of all arguments passed to the script. The $* holds list of all arguments passed to the script.

What is the role of $0 $@ $* variable is shell 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.


2 Answers

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)

like image 89
Mark Byers Avatar answered Oct 12 '22 04:10

Mark Byers


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

like image 22
Art Swri Avatar answered Oct 12 '22 03:10

Art Swri