0

I've got a function in bash that takes an array as argument

in my case the array is made of "false" values

I define this array in a main script and then i call the function

my_function my_array[@]

where my_function is defined this way

function my_function(){
arg_array=("${!1}")

arg_array[2]="true"
}

but if i print the array in the main script i see that the array hasn't been modified. Actually the function modifies the "copy" of the argument array and not the array itself. How can I let the function to modify the source array ( in other programming languages is related to "global" variables..)?

thanks

  • http://stackoverflow.com/q/1063347/1030675 – choroba Oct 21 '14 at 11:31
  • 1
    You can have the function modify the global by using the global and not playing the indirection games to "pass" the array as an argument. Alternatively see http://mywiki.wooledge.org/BashFAQ/006#Assigning_indirect.2Freference_variables – Etan Reisner Oct 21 '14 at 12:44

1 Answers1

2

You are passing, in effect, the names of each element of the array. Just pass the name of the array itself. Then use declare to set the value of any particular element using indirect parameter expansion.

function my_function(){
    elt2="$1[2]"
    declare "$elt2=true"       
}

my_function my_array

In bash 4.3, named references make this much simpler.

function my_function () {
    declare -n arr=$1
    arr[2]=true
}

my_function my_array

This only makes sense, though, if you intend to use my_function with different global arrays. If my_function is only intended to work with the global my_array, then you aren't gaining anything by this: just work with the global as-is.

function my_function () {
    my_array[2]=true
}
chepner
  • 497,756
  • 71
  • 530
  • 681