[关闭]
@ysongzybl 2015-04-30T20:26:14.000000Z 字数 1268 阅读 1869

Bash pass array as function parameter

bash


In function body, refer array parameter using ${!1} instead of ${1}.

Example:

  1. function a(){
  2. x=$1
  3. y=$2
  4. echo "x = ${x} y = ${y}"
  5. }
  6. a hal eos
  7. arr="10 11 12 13"
  8. function b(){
  9. nums=$(echo ${!1}| tr ' ' '\n')
  10. for e in "${nums[@]}"
  11. do
  12. echo "$e"
  13. done
  14. }
  15. b arr

Output:

  1. x = hal y = eos
  2. 10
  3. 11
  4. 12
  5. 13

Another complex exmaple:

  1. takes_ary_as_arg()
  2. {
  3. declare -a argAry1=("${!1}")
  4. echo "${argAry1[@]}"
  5. declare -a argAry2=("${!2}")
  6. echo "${argAry2[@]}"
  7. }
  8. try_with_local_arys()
  9. {
  10. # array variables could have local scope
  11. local descTable=(
  12. "sli4-iread"
  13. "sli4-iwrite"
  14. "sli3-iread"
  15. "sli3-iwrite"
  16. )
  17. local optsTable=(
  18. "--msix --iread"
  19. "--msix --iwrite"
  20. "--msi --iread"
  21. "--msi --iwrite"
  22. )
  23. takes_ary_as_arg descTable[@] optsTable[@]
  24. }
  25. try_with_local_arys

Modified from this example, give a more complicated exmaple below.

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

  1. #!/bin/bash
  2. arr="10 11 12 13"
  3. function f(){
  4. source test.sh
  5. takes_ary_as_arg $1
  6. }
  7. f arr
  1. #!/bin/bash
  2. takes_ary_as_arg(){
  3. declare -a argAry1=("${!1}")
  4. nums=(`echo "${argAry1[@]}"`)
  5. for i in "${nums[@]}"
  6. do
  7. echo $i
  8. done
  9. }
  1. 10
  2. 11
  3. 12
  4. 13

Reference

http://stackoverflow.com/questions/1063347/passing-arrays-as-parameters-in-bash

添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注