Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing arrays as parameters in bash

Tags:

arrays

bash

How can I pass an array as parameter to a bash function?

Note: After not finding an answer here on Stack Overflow, I posted my somewhat crude solution myself. It allows for only one array being passed, and it being the last element of the parameter list. Actually, it is not passing the array at all, but a list of its elements, which are re-assembled into an array by called_function(), but it worked for me. If someone knows a better way, feel free to add it here.

like image 355
DevSolar Avatar asked Jun 30 '09 12:06

DevSolar


People also ask

Can you pass an array as a parameter?

Arrays can be passed as arguments to method parameters. Because arrays are reference types, the method can change the value of the elements.


2 Answers

You can pass multiple arrays as arguments using something like this:

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 

will echo:

sli4-iread sli4-iwrite sli3-iread sli3-iwrite   --msix  --iread --msix  --iwrite --msi   --iread --msi   --iwrite 

Edit/notes: (from comments below)

  • descTable and optsTable are passed as names and are expanded in the function. Thus no $ is needed when given as parameters.
  • Note that this still works even with descTable etc being defined with local, because locals are visible to the functions they call.
  • The ! in ${!1} expands the arg 1 variable.
  • declare -a just makes the indexed array explicit, it is not strictly necessary.
like image 164
Ken Bertelson Avatar answered Oct 02 '22 11:10

Ken Bertelson


Note: This is the somewhat crude solution I posted myself, after not finding an answer here on Stack Overflow. It allows for only one array being passed, and it being the last element of the parameter list. Actually, it is not passing the array at all, but a list of its elements, which are re-assembled into an array by called_function(), but it worked for me. Somewhat later Ken posted his solution, but I kept mine here for "historic" reference.

calling_function() {     variable="a"     array=( "x", "y", "z" )     called_function "${variable}" "${array[@]}" }  called_function() {     local_variable="${1}"     shift     local_array=("${@}") } 
like image 36
DevSolar Avatar answered Oct 02 '22 13:10

DevSolar