I have these two functions:
function two() {
local -a -x var=( ${var[@]} )
echo "${var[@]}"
}
function one() {
local -a -x var=(11 22 33)
two
}
If I call one, then nothing is printed. Why is that?
nothing is print. Why is that?
Here you're having the same identifier name var in both the functions
The var you defined in one could accessed by two because two is called from one. However,
when declaring and setting a local variable in a single command, apparently the order of operations is to first set the variable, and only afterwards restrict it to local scope.
So in
local -a -x var=( "${var[@]}" )
the ${var[@]} part will be empty as the variable var is set local first.
To verify this you could change the variable name in one to var1 and and in two do
local -a -x var=( "${var1[@]}" ) # var1 though local to one should be accessible here.
You could use @inian's answer as a work-around to pass variables easily and yet not bother about such dark corners in bash.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With