$* 和 $@ 都表示传递给函数或脚本的所有参数,不被双引号(" ")包含时,都以"$1" "$2" … "$n" 的形式输出所有参数。
但是当它们被双引号(" ")包含时,"$*" 会将所有的参数作为一个整体,以"$1 $2 … $n"的形式输出所有参数;"$@" 会将各个参数分开,以"$1" "$2" … "$n" 的形式输出所有参数。
下面的例子可以清楚的看到 $* 和 $@ 的区别:
1 #!/bin/bash 2 echo "\$*=" $* 3 echo "\"\$*\"=" "$*" 4 5 echo "\$@=" $@ 6 echo "\"\$@\"=" "$@" 7 8 echo "print each param from \$*" 9 for var in $* 10 do 11 echo "$var" 12 done 13 14 echo "print each param from \$@" 15 for var in $@ 16 do 17 echo "$var" 18 done 19 20 echo "print each param from \"\$*\"" 21 for var in "$*" 22 do 23 echo "$var" 24 done 25 26 echo "print each param from \"\$@\"" 27 for var in "$@" 28 do 29 echo "$var" 30 done
执行 sh test "a" "b" "c" "d",看到下面的结果: