arrays - Let a function modify a global variable -
i've got function in bash takes array argument
in case array made of "false" values
i define array in main script , phone call function
my_function my_array[@]
where my_function defined way
function my_function(){ arg_array=("${!1}") arg_array[2]="true" }
but if print array in main script see array hasn't been modified. function modifies "copy" of argument array , not array itself. how can allow function modify source array ( in other programming languages related "global" variables..)?
thanks
you passing, in effect, names of each element of array. pass name of array itself. utilize declare
set value of 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 create much simpler.
function my_function () { declare -n arr=$1 arr[2]=true } my_function my_array
this makes sense, though, if intend utilize my_function
different global arrays. if my_function
intended work global my_array
, aren't gaining this: work global as-is.
function my_function () { my_array[2]=true }
arrays bash function global-variables
No comments:
Post a Comment