shell中数组传参—— $@ 和 $* 的对比

### 数组传参,保持原有数组(每个元素含有IFS)的情况
[tyler@tyler tools]$ cat test.sh

#!/bin/bash

function test()

{

    newArr=("$@")

    echo "${newArr[@]}"

    for i in "${newArr[@]}"

    do

        echo $i

    done

}

arr=("hahah   ahha" "xixix   xixi")

test "${arr[@]}"

 

[tyler@tyler tools]$ ./test.sh

hahah   ahha xixix   xixi

hahah ahha

xixix xixi

[tyler@tyler tools]$

### 对比 $@ 和 $*

[tyler@tyler tools]$ cat test.sh

#!/bin/bash

function test()

{

    newArr=("$@")

    echo "${newArr[*]}"

    for i in "${newArr[*]}"

    do

        echo $i

    done  

}

arr=("hahah   ahha" "xixix   xixi")

test "${arr[*]}"

 

[tyler@tyler tools]$ ./test.sh

hahah   ahha xixix   xixi

hahah ahha xixix xixi

[tyler@tyler tools]$

### 几个地方需要注意

# 传入时 test "${arr[@]}" 必须带引号,用 $@ ,才能

原样数组传入,这是因为 $@ 在引号下会将每个元素,

带上引号传过去

# 函数内重组数组,不能用 echo 输出重组;echo 重组

不带引号会将原样格式当一个元素传给 newArr,echo 重

组带引号,会识别传入的每个元素内的 IFS

# 最后,循环遍历时。也必须给新数组加上引号

 

你可能感兴趣的:(linux)