Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

bash - Passing multiple distinct arrays to a shell function

Because shells other than ksh do not support pass-by-reference, how can multiple arrays be passed into a function in bash without using global variables, and in a way which allows any legal variable content to be included as an array element (no reserved sigils)?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Since bash 4.3

As of 2016, modern bash supports pass-by-reference (a.k.a nameref attribute) as:

demo_multiple_arrays() {
  local -n _array_one=$1
  local -n _array_two=$2
  printf '1: %q
' "${_array_one[@]}"
  printf '2: %q
' "${_array_two[@]}"
}

array_one=( "one argument" "another argument" )
array_two=( "array two part one" "array two part two" )

demo_multiple_arrays array_one array_two

See also declare -n in the man page.


Before bash 4.3

This can be done safely by using a calling convention which puts number-of-arguments before each array, as such:

demo_multiple_arrays() {
  declare -i num_args array_num;
  declare -a curr_args;
  while (( $# )) ; do
    curr_args=( )
    num_args=$1; shift
    while (( num_args-- > 0 )) ; do
      curr_args+=( "$1" ); shift
    done
    printf "$((++array_num)): %q
" "${curr_args[@]}"
  done
}

This can then be called as follows:

array_one=( "one argument" "another argument" )
array_two=( "array two part one" "array two part two" )
demo_multiple_arrays 
  "${#array_one[@]}" "${array_one[@]}" 
  "${#array_two[@]}" "${array_two[@]}"

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...