我引用Passing arrays as parameters in bash,但失败了。这是我的测试脚本(两个bash 3.0)
bash版
GNU bash, version 3.00.16(1)-release (sparc-sun-solaris2.10)
Copyright (C) 2004 Free Software Foundation, Inc.
脚本t.sh
fn() {
local i
local v1="$1"
local v2="$2"
local v3="$3"
echo "v1=$1"
echo "v2=$2"
echo "v3=$3"
declare -a a1=("${!1}")
declare -a a2=("${!2}")
echo "a1:"
for i in ${!a1[*]} ; do
echo " ${a1[$i]}"
done
echo "a2:"
for i in ${!a2[*]} ; do
echo " ${a2[$i]}"
done
}
caller() {
local a=("a1 a2" "a3" "a4")
local b=("b1" "b2" "b3" "b4")
echo "method 1:"
fn "${a[@]}" "${b[@]}" $1 $2 $3
echo "method 2:" # workable on bash 4.2.45
fn a[@] b[@] $1 $2 $3
}
caller c
输出
method 1:
v1=(a1 a2 a3 a4)
v2=(b1 b2 b3 b4)
v3=c
a1:
a2:
method 2:
v1=a[@]
v2=b[@]
v3=c
t.sh: array assign: line 10: syntax error near unexpected token `('
t.sh: array assign: line 10: `(a1 a2 a3 a4)'
预期产出
...
a1:
a1 a2
a3
a4
a2:
b1
b2
b3
b4
答案 0 :(得分:0)
我不确定您在哪里遇到此问题,但我已确认Bash 3.2.25
的操作:
./caller.sh
method 1:
v1=a1 a2
v2=a3
v3=a4
a1:
a2:
method 2:
v1=a[@]
v2=b[@]
v3=c
a1:
a1 a2
a3
a4
a2:
b1
b2
b3
b4
03:36 lakehouse~/scr/tmp> bash --version
GNU bash, version 3.2.25(1)-release (i586-suse-linux-gnu)
Copyright (C) 2005 Free Software Foundation, Inc.