when I am working on shell script, I am little frusturate on $@ and “$@” problem. So, I write a shell script to do some testing. like following.
func()
{
local a="$@"
for i in "$a"; do
echo "$i ****"
done
}
func000()
{
local a="$@"
for i in $a; do
echo "$i ****"
done
}
func0()
{
local a=$@
for i in "$a"; do
echo "$i ****"
done
}
func00()
{
local a=$@
for i in $a; do
echo "$i ****"
done
}
func1()
{
for i in "$@"; do
echo "$i ****"
done
}
func2()
{
for i in $@; do
echo "$i ****"
done
}
func "a b c"
func a b c
echo "-----------"
func0 "a b c"
func0 a b c
echo "-----------"
func00 "a b c"
func00 a b c
echo "-----------"
func000 "a b c"
func000 a b c
echo "-----------"
func1 "a b c"
func1 a b c
echo "-----------"
func2 "a b c"
func2 a b c
a b c ****
a b c **** func
-----------
a b c **** func0
a b c ****
-----------
a **** func00
b ****
c ****
a ****
b ****
c ****
------------
a **** func000
b ****
c ****
a ****
b ****
c ****
-----------
a b c **** func1 //this has the result that I want.
a ****
b ****
c ****
-----------
a **** func2
b ****
c ****
a ****
b ****
c ****
As far as I remember, when using $@, we have to use double quoate, otherwise something will break. Therefore, I know some of functions definitely not work properly. (I still test it anyway)
Only func1 gives me a desire result, however, the thing is I want to assign “$@” to a variable. by reviewing func0, func000, func0, func00 results, none of those give me correct stuff. So, I am hoping someone can help me out.
In addition, I know sh and bash has difference. If someone can point me out in which condition something could break I will be so glad. Thanks.
update
I should say, this result of this script, it comes to the version of bash or sh, or freebsd sh vs linux sh.
I could be wrong, if so, just point it out, thanks a lot.
in old sh, freebsd sh, in which we do not have array, obviously, array assignment could not get working, the alternative is to use string like what I did in func000, local a=”$a”; for i in $a; do …
If using linux sh 4.5 (tested), or bash, see my answer below.
update, thanks to @jordanm, I realize this is the difference between bash and old sh version somehow.
this is a solution in bash or sh 4.2. in old sh, this might not be working.