@ysongzybl
2015-04-30T20:26:14.000000Z
字数 1268
阅读 1944
bash
In function body, refer array parameter using ${!1} instead of ${1}.
function a(){x=$1y=$2echo "x = ${x} y = ${y}"}a hal eosarr="10 11 12 13"function b(){nums=$(echo ${!1}| tr ' ' '\n')for e in "${nums[@]}"doecho "$e"done}b arr
Output:
x = hal y = eos10111213
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 scopelocal 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/basharr="10 11 12 13"function f(){source test.shtakes_ary_as_arg $1}f arr
#!/bin/bashtakes_ary_as_arg(){declare -a argAry1=("${!1}")nums=(`echo "${argAry1[@]}"`)for i in "${nums[@]}"doecho $idone}
./main.sh
10111213
http://stackoverflow.com/questions/1063347/passing-arrays-as-parameters-in-bash