Shell特殊变量:$*和$@的区别

时间:2021-11-21 15:35:02
$* 和 $@ 都表示传递给函数或者脚本的所有参数,不被双引号(" ")包含时,两者效果相同,都以"$1" "$2" … "$n" 的形式输出所有参数。


但是当它们被双引号(" ")包含时,"$*" 会将所有的参数作为一个整体,以"$1 $2 … $n"的形式输出所有参数;"$@" 会将各个参数分开,以"$1" "$2" … "$n" 的形式输出所有参数。


例如:

#!/bin/bash
echo "\$*=" $*
echo "\"\$*\"=" "$*"

echo "\$@=" $@
echo "\"\$@\"=" "$@"

echo "print each param from \$*"
for var in $*
do
echo "$var"
done

echo "print each param from \$@"
for var in $@
do
echo "$var"
done

echo "print each param from \"\$*\""
for var in "$*"
do
echo "$var"
done

echo "print each param from \"\$@\""
for var in "$@"
do
echo "$var"
done


执行 ./test.sh "a" "b" "c" "d",看到下面的结果:

$*=  a b c d
"$*"= a b c d
$@=  a b c d
"$@"= a b c d
print each param from $*
a
b
c
d
print each param from $@
a
b
c
d
print each param from "$*"
a b c d
print each param from "$@"
a
b
c
d