在Bash脚本中,$*和$@都用于表示执行脚本时所传入的参数。先通过一个例子看看他们的区别:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | #!/bin/bash # testvar.sh echo "-------------ISF is set to \"-seperator\" ------------" IFS="-seperator"; # 注意 seperator前有一个减号(-) for i in "$@"; do echo "@ '$i'"; done for i in "$*"; do echo "* '$i'"; done
echo "-------------ISF is set to null ------------------------" IFS= for i in "$@"; do echo "@ '$i'"; done for i in "$*"; do echo "* '$i'"; done
echo "-------------ISF is unset ------------------------" unset IFS for i in "$@"; do echo "@ '$i'"; done for i in "$*"; do echo "* '$i'"; done
echo "---------$* and $@ are not put into double quotes(\"\")-------" for i in $@; do echo "@ '$i'"; done for i in $*; do echo "* '$i'"; done |
执行的结果如下:
-------------ISF is set to "-seperator" ------------
@ 'aa'
@ 'bb'
@ 'cc'
* 'aa-bb-cc'
-------------ISF is set to null ------------------------
@ 'aa'
@ 'bb'
@ 'cc'
* 'aabbcc'
-------------ISF is unset ------------------------
@ 'aa'
@ 'bb'
@ 'cc'
* 'aa bb cc'
---------aa bb cc and aa bb cc are not put into double quotes("")-------
@ 'aa'
@ 'bb'
@ 'cc'
* 'aa'
* 'bb'
* 'cc'
由此可见,
1) 当不加双引号("")时, $*,$@被展开时的行为是一样的;
2) 当$*,$@都被放到双引号("")内;
2.1) 如果设置了变量IFS的值并且该值非空, 则$*被展开时使用${IFS}的第一个字符将所有参数(除了参数$0)连接起来, 即"$1c$2c$3c...",其中c表示${IFS}的第一个字符;
2.2) 如果变量IFS为空, 则$*被展开时只是将所有参数(除了参数$0)简单连接起来, 即 “$1$2$3..."
2.3)如果变量IFS没有被定义, 则$*被展开时使用空格字符将所有参数(除了参数$0) 连接起来, 即"$1 $2 $3 ..."
但$@的展开和没有加双引号的情形是一致的。
转载于:https://blog.51cto.com/kusorz/1711331