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

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

 

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值