关闭

shell 函数参数为数组传递

2209人阅读 评论(0) 收藏 举报
分类:

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

0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:40294次
    • 积分:704
    • 等级:
    • 排名:千里之外
    • 原创:13篇
    • 转载:87篇
    • 译文:0篇
    • 评论:0条
    文章分类