Skip to content
Advertisement

Get variable name while iterating over array in bash

What I have is an array with some variables. I can iterate to get the values of those vars but what I need is actually their names (values will be used elsewhere).

Going with var[i] won’t work cause I will have different names. I guess I could workaround this by creating another array with the names – something similar to this: Getting variable values from variable names listed in array in Bash

But I’m wondering if there is a better way to do this.

var1=$'1'
var2=$'2'
var3=$'3'

Array=( $var1 $var2 $var3)

for ((i=0; i<${#Array[@]}; i++))
do
  echo ${Array[i]}
done

Is:

>1
>2
>3

Should be:

>var1
>var2
>var3

Advertisement

Answer

It sounds like you want an associative array.

# to set values over time
declare -A Array=( ) || { echo "ERROR: Need bash 4.0 or newer" >&2; exit 1; }
Array[var1]=1
Array[var2]=2
Array[var3]=3

This can also be assigned at once:

# or as just one assignment
declare -A Array=( [var1]=1 [var2]=2 [var3]=3 )

Either way, one can iterate over the keys with "${!Array[@]}", and retrieve the value for a key with ${Array[key]}:

for var in "${!Array[@]}"; do
  val="${Array[$var]}"
  echo "$var -> $val"
done

…will, after either of the assignments up top, properly emit:

var1 -> 1
var2 -> 2
var3 -> 3
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement