How can I index an array by name in bash

I have the bash code below, I just want to know how to find an array by its name:

#!/bin/bash

arr=("object1" "object2")

name="arr"

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

      

below:

object0 = object1
object1 =

      

I am wondering why I am not able to index the second element and how to do this?

+3


source to share


1 answer


Use this syntax:

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

      

Your other code is fine.



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

You can always use this hack:

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

      

+3


source







All Articles