3

I have such bash code below, I just want to know how to find an array by it's name:

#!/bin/bash

arr=("object1" "object2")

name="arr"

array=${!name}
echo object0 = ${array[0]}
echo object1 = ${array[1]}

outputs below:

object0 = object1
object1 =

I'm wondering why I cannot index the second element and how can I do that!!!

2
  • You fail to get the second element because $arr when arr is an array yields the zeroth element of the array (only). So the assignment array=${!name} assigns a single value to array, and then you can't pick up multiple values from it. Commented May 8, 2015 at 5:47
  • Thank you, I googled it, and now I understand what does '@' mean! Commented May 8, 2015 at 6:35

1 Answer 1

3

Use this syntax:

name="arr[@]"
array=("${!name}")

Your other code is fine.

Or if you have this passed as a variable, name="arr"

You can always use this hack:

name_temp="$name[@]"
array=("${!name_temp}")
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, this really solve my problem, yeah, I have the output that I expected!

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.