2

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.

phydeauxman
  • 1,432
  • 3
  • 26
  • 48

1 Answers1

2

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.

M. Nejat Aydin
  • 9,597
  • 1
  • 7
  • 17
  • 1
    Thanks for the quick reply. That works as desired to expand the variable name but now how do I use that to also get the value of that variable using `$v`? – phydeauxman Feb 24 '21 at 13:30
  • 1
    @phydeauxman The `!` introduces a level of indirection: `${!v}`. Remove the `#` before `echo` in the updated answer and examine the output. – M. Nejat Aydin Feb 24 '21 at 13:44
  • Is there a method of indirect expansion that will work on the end of variable names? What if I had several variables that were of the format: `myvar1_var` , `myvar2_var`, `myvar3_var`. Is there something like ${!*_var} that do an indirect expansion of each of these variables? – phydeauxman Feb 25 '21 at 12:12
  • 1
    @phydeauxman As far as I know, there is no such a direct method, but something like that could be used to list variable names ending with `_var`: `(set -o posix ; set) | sed -n '/_var=/s/=.*//p'` – M. Nejat Aydin Feb 25 '21 at 12:56