Monday, May 09, 2005

Wats the difference between $* and $@

You probably know the difference between "$@" and $*. Both stand for "all arguments specified on the command line". "$@" does preserve whitespace, while $* does not.
Lets make this more clear.create a script named “quote” as follows…

========================== vi quote ==============
cat "$*"
cat "$@"
~
======================end==============

now make it executable.
Make another two files as follows
============vi test1=============
hi this is test 1


============= vi test2====================
this is test2


$ quote test1 test2
cat: cannot open test1 test2
hi this is test 1

this is test2

wats the hell is going on here..?? first its telling It cant open files.n then opening it…!!!
Actually wats happening inside is first Mr “$*” tried…. And expanded the command as “test1 test2”. That means it told the shell to cat a file named “test1 test2”. And this is wrong. Thus shell replied “ no no…there is no single file named ‘test1 test2’”. Then came another partner Mr “$@” inside the “quote” file. It took a different approach to expand things .wat it did is that it told the shell to cat two files named “test1’ and “test2”. And shell happily did that.
In brief
“$*” expands to “test1 test2”
“$@” expands to “test1” “test2”

Labels:

0 Comments:

Post a Comment

<< Home