Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between $@ and $* in shell script? [duplicate]

Tags:

linux

bash

shell

in my script.sh:

aa=$@
bb=$*
echo $aa
echo $bb

when running it:

 source script.sh a b c d e f g

I get:

a b c d e f g
a b c d e f g

What is the difference between $@ and $* ?

like image 581
0x90 Avatar asked Mar 24 '13 09:03

0x90


People also ask

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

$0 Stores the first word of the entered command (the name of the shell program). $* Stores all the arguments that were entered on the command line ($1 $2 ...). "$@" Stores all the arguments that were entered on the command line, individually quoted ("$1" "$2" ...).

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

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


1 Answers

There are no difference between $* and $@, but there is a difference between "$@" and "$*".

$ cat 1.sh
mkdir "$*"

$ cat 2.sh
mkdir "$@"

$ sh 1.sh a "b c" d

$ ls -l
total 12
-rw-r--r-- 1 igor igor   11 mar 24 10:20 1.sh
-rw-r--r-- 1 igor igor   11 mar 24 10:20 2.sh
drwxr-xr-x 2 igor igor 4096 mar 24 10:21 a b c d

We gave three arguments to the script (a, b c and d) but in "$*" they all were merged into one argument a b c d.

$ sh 2.sh a "b c" d

$ ls -l
total 24
-rw-r--r-- 1 igor igor   11 mar 24 10:20 1.sh
-rw-r--r-- 1 igor igor   11 mar 24 10:20 2.sh
drwxr-xr-x 2 igor igor 4096 mar 24 10:21 a
drwxr-xr-x 2 igor igor 4096 mar 24 10:21 a b c d
drwxr-xr-x 2 igor igor 4096 mar 24 10:21 b c
drwxr-xr-x 2 igor igor 4096 mar 24 10:21 d

You can see here, that "$*" means always one single argument, and "$@" contains as many arguments, as the script had. "$@" is a special token which means "wrap each individual argument in quotes". So a "b c" d becomes (or rather stays) "a" "b c" "d" instead of "a b c d" ("$*") or "a" "b" "c" "d" ($@ or $*).

Also, I would recommend this beautiful reading on the theme:

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

like image 139
Igor Chubin Avatar answered Oct 21 '22 14:10

Igor Chubin