shell数组${arr[*]}和${arr[@]}区别
引用数组中所有元素时${arr[*]}和${arr[@]}是有细微区别的
Example:
-
#!/bin/sh function showarr(){ arr=$1 for b in ${arr[*]};do echo $b done return 0 } regions=('aa pp' 'bb' 'cc') showarr $regions exit 0
$regions其实只引用了数组的第一个元素
-
#!/bin/sh function showarr(){ arr=$1 for b in ${arr[*]};do echo $b done return 0 } regions=('aa pp' 'bb' 'cc') showarr ${regions[*]} echo ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ showarr ${regions[@]} exit 0
引用了数组全部元素,但是showarr函数中arr变量只获取了第一个参数的值 "aa"
-
#!/bin/sh function showarr(){ arr=$1 for b in ${arr[*]};do echo $b done return 0 } regions=('aa pp' 'bb' 'cc') showarr "${regions[*]}" echo ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ showarr "${regions[@]}" exit
此种情况跟 $* $@比较类似,${regions[*]}把参数打散,作为一个字符串整体传递,原有参数结构被破坏
${regions[@]}保持了原参数结构,因此$1其实为 'aa pp' -
#!/bin/sh function showarr(){ arr=$1 for b in ${arr[*]};do echo $b done echo "\$1: $1" echo "\$2: $2" echo "\$3: $3" return 0 } regions=('aa pp' 'bb' 'cc') showarr "${regions[*]}" echo ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ showarr "${regions[@]}" exit 0
改进后的脚本执行情况验证了我们的猜想
- 结论: $@ $* ${arr[@]} ${arr[*]} 类似,加不加"", 使用@还是*根据实际情况选择
- 不加""的时候,@ 和 * 完全一样,加""时,@可以保持原有参数结构,*将原有参数结构打乱
- shell对 "$@"会做特殊处理,"$*"可以认为是普通字符串
#!/bin/sh for p in "$*";do echo $p done echo ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ for p in "$@";do echo $p done
"$@" 已经不是简单的字符串了