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:
With your
${...}
statement inupdate_array()
, the${..}
syntax to use a variable, not define it.Example:
Working around that the array name is stored in a variable.
Not working:
Working:
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:
which prints, correctly: