views:

37

answers:

2

Hi,

In a bash script, I would like to put the following code that assigns values to each element of several arrays into a function

for (( i=0 ; i < ${#themes[@]} ; i+=1 )); do  
  c_bit_mins[i]=-5  
  c_bit_maxs[i]=15  
  gamma_bit_mins[i]=-15  
  gamma_bit_maxs[i]=3  
done

i.e. something like

function set_values()
{
for (( i=0 ; i < ${#themes[@]} ; i+=1 )); do  
  c_bit_mins[i]=-5  
  c_bit_maxs[i]=15  
  gamma_bit_mins[i]=-15  
  gamma_bit_maxs[i]=3  
done
}

How to do it? Especially when these arrays are not seen as global inside the function.

Thanks and regards!

+1  A: 

You can make a variable local by using the local command:

local c_bit_mins c_bit_maxs gamma_bit_mins gamma_bit_maxs

However, you can't "return" an array out of a shell function. The return value of a shell function is always an integer. Non-integer values are typically "returned" by echoing them and reading them back in using $(...) in the surrounding program. But that will be completely weird to do with arrays and four of them.

Peter Eisentraut
+1  A: 

The arrays are global unless you declare them to be local.

$ unset a
$ test() { echo ${a[3]}; a[4]=456; }
$ a[3]=123
$ test
123
$ echo ${a[4]}
456
$ echo ${a[3]}
123
Dennis Williamson