您的位置:首页 > 运维架构 > Shell

shell 函数参数为数组传递

2015-11-21 19:30 435 查看
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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: