0

Who can help to give a shell script example to show the difference between $* and $@?

The following is my script, but it can't tell the difference. Anybody can give a good example?

$ cat internalVar.sh #!/bin/bash # internalVar.sh var1 var2 echo "\$? = " $? export IFS="_" echo "\$@ = " $@ " == several parameters?" j=1 for i in $@ do echo "var $j = $i" j=$((j+1)) done echo "\$* = " $* " == a single string" j=1 for i in $* do echo "var $j = $i" j=$((j+1)) done echo "\$# = " $# echo "\$0 = " $0 echo "\$$ = " $$ $ export IFS="c" [$ ./internalVar.sh par1 "par meter 2" par3 $? = 0 $@ = par1 par meter 2 par3 == several parameters? var 1 = par1 var 2 = par meter 2 var 3 = par3 $* = par1 par meter 2 par3 == a single string var 1 = par1 var 2 = par meter 2 var 3 = par3 $# = 3 $0 = ./internalVar.sh $$ = 4638 
3
  • 1
    Your script can't tell the difference because it's not using appropriate quotes. Without quoting correctly, there is no difference (and you get a whole lot of bugs). Commented May 6, 2016 at 1:41
  • @CharlesDuffy Duh, of course there is a duplicate. I must have thought "it's not asking about var = val, it must be new ;) Commented May 6, 2016 at 1:46
  • Thanks guys, I got it. Commented May 6, 2016 at 4:06

1 Answer 1

3

How about this:

$ set 'arg1a arg1b' 'arg2a arg2b' 'arg3a arg3b' $ for arg in "$@"; do echo "$arg"; done arg1a arg1b arg2a arg2b arg3a arg3b $ for arg in "$*"; do echo "$arg"; done arg1a arg1b arg2a arg2b arg3a arg3b $ for arg in $@; do echo "$arg"; done arg1a arg1b arg2a arg2b arg3a arg3b $ for arg in $*; do echo "$arg"; done arg1a arg1b arg2a arg2b arg3a arg3b 

This loops over the expansion, which in the first case "$@" is a separate parameter for each positional parameter, and in the second case "$*" a single string.

The third and fourth case, the unquoted ones, perform word splitting and are no different from each other.

See also the manual, "Special Parameters".

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.