shell 函数参数为数组传递

本文介绍在Bash脚本中如何将数组作为参数传递给函数。文章提供了两种方法:一种是通过传递数组元素的方式;另一种是通过传递数组名称的方式。这两种方法都能有效地解决在Bash中使用函数处理数组的需求。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

You cannot pass an array, you can only pass its elements (i.e. the expanded array).

#! /bin/bash
function f() {
    a=("$@")
    ((last_idx=${#a[@]} - 1))
    b=${a[last_idx]}
    unset a[last_idx]

    for i in "${a[@]}" ; do
        echo "$i"
    done
    echo "b: $b"
}

x=("one two" "LAST")
b='even more'

f "${x[@]}" "$b"
echo ===============
f "${x[*]}" "$b"

The other possibility would be to pass the array by name:

#! /bin/bash
function f() {
    name=$1[@]
    b=$2
    a=("${!name}")

    for i in "${a[@]}" ; do
        echo "$i"
    done
    echo "b: $b"
}

x=("one two" "LAST")
b='even more'

f x "$b"



http://stackoverflow.com/questions/16461656/bash-how-to-pass-array-as-an-argument-to-a-function

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值