Ubuntu – how to pass array into function and updates to array are reflected outsite function

bashcommand linescripts

I am trying to pass a array into a function and whatever changes made to the array is reflected outside the function

function update_array()
{   
    ${1[0]}="abc" # trying to change zero-index array to "abc" , 
                  #  bad substitution error


}

foo=(foo bar)

update_array foo[@]

for i in ${foo[@]}
    do
       echo "$i" # currently changes are not reflected outside the function

    done

My questions are

1) How do i access the index array eg: zero index array , in the function , what is the syntax for it

2) How do i make changes to this index array so that the changes are reflected outsite the function also

Best Answer

Several problems, in logical order of fixing:

  • Style (pet peeve)
  • With your ${...} statement in update_array(), the ${..} syntax to use a variable, not define it.

    Example:

    foo[0]=abc  # assigns 'abc' to foo[0]
    
  • Working around that the array name is stored in a variable.

    Not working:

    $1[0]=abc
    

    Working:

    declare -g "$1[0]=abc"  # -g arg is for a global variable
    
  • Passing an argument to update_array() should pass the variable name (foo in this case), not the contents of the array. foo[@] is nothing special, it is a completely normal string (in Bash).

  • Variable expansion with ${foo[@]} should be double-quoted.

Working version of the code is below:

update_array() {   
    declare -g "$1[0]=abc"
}

foo=(foo bar)

update_array foo

for i in "${foo[@]}"; do
    echo "$i"
done

## Following line added by me for further clarification
declare -p foo

which prints, correctly:

abc
bar
declare -a foo='([0]="abc" [1]="bar")'