如何在Bash中将数组作为参数传递给函数 [英] How to pass array as an argument to a function in Bash
问题描述
我们知道,在bash编程中,传递参数的方式是$1
,...,$N
.但是,我发现将数组作为参数传递给接收多个参数的函数并不容易.这是一个示例:
As we know, in bash programming the way to pass arguments is $1
, ..., $N
. However, I found it not easy to pass an array as an argument to a function which receives more than one argument. Here is one example:
f(){
x=($1)
y=$2
for i in "${x[@]}"
do
echo $i
done
....
}
a=("jfaldsj jflajds" "LAST")
b=NOEFLDJF
f "${a[@]}" $b
f "${a[*]}" $b
如上所述,函数f
接收两个参数:第一个参数分配给作为数组的x
,第二个参数分配给y
.
As described, function f
receives two arguments: the first is assigned to x
which is an array, the second to y
.
f
可以通过两种方式调用.第一种方法使用"${a[@]}"
作为第一个参数,结果为:
f
can be called in two ways. The first way use the "${a[@]}"
as the first argument, and the result is:
jfaldsj
jflajds
第二种方法使用"${a[*]}"
作为第一个参数,结果是:
The second way use the "${a[*]}"
as the first argument, and the result is:
jfaldsj
jflajds
LAST
两个结果都不如我所愿.那么,有没有人知道如何正确地在函数之间传递数组?
Neither result is as I wished. So, is there anyone having any idea about how to pass array between functions correctly?
推荐答案
您不能传递数组,只能传递其元素(即扩展数组).
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"
这篇关于如何在Bash中将数组作为参数传递给函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!