Bash variable name expansion in a loop

Viewed 114

I have several variables that have the name format of:

var0_name
var1_name
var2_name

And I want to be able to loop thru them in a manner like this:

for i in {0..2}
do
  echo "My variable name = " ${var[i]_name}
done

I have tried several different ways to get this expansion to work but have had no luck so far.

1 Answers

Using the ${!prefix*} expansion in bash:

#!/bin/bash

var0_name=xyz
var1_name=asdf
var2_name=zx

for v in ${!var*}; do
    echo "My variable name = $v"
    # echo "Variable '$v' has the value of '${!v}'"
done

or equivalently, by replacing the for loop with:

printf 'My variable name = %s\n' ${!var*}

You may also consider reading the Shell Parameter Expansion for detailed information on all forms of parameter expansions in bash, including those that are used in the answer as well.

Related