如何将数组作为参数传递给 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屋!