@ysongzybl
2015-04-30T20:26:14.000000Z
字数 1268
阅读 1869
bash
In function body, refer array parameter using ${!1}
instead of ${1}
.
function a(){
x=$1
y=$2
echo "x = ${x} y = ${y}"
}
a hal eos
arr="10 11 12 13"
function b(){
nums=$(echo ${!1}| tr ' ' '\n')
for e in "${nums[@]}"
do
echo "$e"
done
}
b arr
Output:
x = hal y = eos
10
11
12
13
takes_ary_as_arg()
{
declare -a argAry1=("${!1}")
echo "${argAry1[@]}"
declare -a argAry2=("${!2}")
echo "${argAry2[@]}"
}
try_with_local_arys()
{
# array variables could have local scope
local descTable=(
"sli4-iread"
"sli4-iwrite"
"sli3-iread"
"sli3-iwrite"
)
local optsTable=(
"--msix --iread"
"--msix --iwrite"
"--msi --iread"
"--msi --iwrite"
)
takes_ary_as_arg descTable[@] optsTable[@]
}
try_with_local_arys
The idea is:
1. define a function f in file A
2. define a function g in file B
3. in function f:
- call function g in B
- pass g an argument of string (seperated by spaces)
- g parses the string argument and display it as an array of elements
#!/bin/bash
arr="10 11 12 13"
function f(){
source test.sh
takes_ary_as_arg $1
}
f arr
#!/bin/bash
takes_ary_as_arg(){
declare -a argAry1=("${!1}")
nums=(`echo "${argAry1[@]}"`)
for i in "${nums[@]}"
do
echo $i
done
}
./main.sh
10
11
12
13
http://stackoverflow.com/questions/1063347/passing-arrays-as-parameters-in-bash