Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

difference between $@ and $* in bash script [duplicate]

Tags:

linux

bash

shell

There are 4 bash snippets below. I call them with ./script.sh a b c

for arg in $@; do 
echo "$arg"
done   ## output "a\nb\nc"

for arg in "$@"; do
echo "$arg"
done  ## output "a\nb\nc" -- I don't know why

for arg in $*; do
echo "$arg"
done  ##    output "a\nb\nc"

for arg in "$*"; do
echo "$arg"
done    ## output "abc"

I don't know what is the exact difference between $@ and $*,
and I think "$@" and "$*" should be the same, but they are not. Why?

like image 854
ruanhao Avatar asked Jan 12 '14 06:01

ruanhao


1 Answers

If you have a script foo.sh:

asterisk "$*"
at-sign "$@"

and call it with:

./foo.sh "a a" "b b" "c c"

it's equivalent to:

asterisk "a a b b c c"
at-sign "a a" "b b" "c c"

Without the quotes, they're the same:

asterisk $*
at-sign $@

would be equivalent to:

asterisk "a" "a" "b" "b" "c" "c"
at-sign "a" "a" "b" "b" "c" "c"
like image 68
millimoose Avatar answered Oct 15 '22 05:10

millimoose