Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setting a local array to its value

Tags:

bash

shell

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?

like image 390
Nikolaos Kakouros Avatar asked Jul 24 '26 01:07

Nikolaos Kakouros


1 Answers

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.

like image 143
sjsam Avatar answered Jul 27 '26 05:07

sjsam



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!