2

I am trying to expand all values in an array I get to through indirect expansion:

> my_array=(coconut banana)
> echo "${my_array[@]}" 
coconut banana
> my_array_name=my_array
> echo ${!my_array_name}
coconut
> echo "${!my_array_name[@]}"
0

I am erroneously using "List of array keys" in the last command because I don't know how to type the right command?

I would like to get:

coconut banana

possibly without resorting to some ugly eval hack.. Example of one suck hack:

> echo \${$my_array_name[@]}
${my_array[@]}
> eval echo \${$my_array_name[@]}
coconut banana

Note

my_array may contain values with spaces!

EDIT

In the function I am writing, my_array_name is set through "$1" so I cannot use that literally.

Similar to: https://unix.stackexchange.com/questions/20171/indirect-return-of-all-elements-in-an-array but I need to avoid using eval to protect from the nasty effects the script would have if the environment was "hacked" just at the right time...

2 Answers 2

4

This should work

my_array_name='my_array[@]'
echo "${!my_array_name}"

After comment : you have to create a string with the name of the array and '[@]', another example

my_array_name="$1"'[@]'
echo "${!my_array_name}"

After comment : test in a function

display_elem() {
  local arrname
  arrname="$1[@]"
  printf "%s\n" "${!arrname}"
}

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

4 Comments

@Robottinosino the my_array comes from your example, you can replace by whatever else
SMART and completely unexpected that bash would fall for that trick! Better than eval, I say!
I second that! Great job, Nahuel!
Maybe this example will work for you: stackoverflow.com/a/30156747/2350426 It indeed does not use the ARRAY name in the function.
1

The problem is my_array_name=my_array. You need to retrieve all values of my_array. Try this instead:

 my_array_name=${my_array[@]}
 echo "${my_array_name[@]}"

1 Comment

I don't know that the name I should use is my_array when executing the code. That itself comes from $1, apologies I did not make that clear. Upvoting anyway, even if this is not a solution for me.

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.