2

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!

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.