bash dynamic (variable) variable names

If you want to reference a bash variable while having the name stored in another variable you can do it as follows:

$ var1=hello
$ var2=var1
$ echo ${!var2}
hello

You store the name of the variable you want to access in, say, var2 in this case. Then you access it with ${!<varable name>} where <variable name> is a variable holding the name of the variable you want to access.


First of all there can not be any space around = in variable declaration in bash.

To get what you want you can use eval.

For example a sample script like yours :

#!/bin/bash
i=0
for name in FIRST SECOND THIRD FOURTH FIFTH; do
    eval "$name"="'$(( $i + 1 ))q;d'"
    printf '%s\n' "${!name}"
    i=$(( $i + 1 ))
done

Prints :

1q;d
2q;d
3q;d
4q;d
5q;d

Use eval cautiously, some people call it evil for some valid reason.

declare would work too :

#!/bin/bash
i=0
for name in FIRST SECOND THIRD FOURTH FIFTH; do
    declare "$name"="$(( $i + 1 ))q;d"
    printf '%s\n' "${!name}"
    i=$(( $i + 1 ))
done

also prints :

1q;d
2q;d
3q;d
4q;d
5q;d

What I get from your code and your desired output (correct me if I'm wrong):
There is no use of the "FIRST"/"SECOND"/... variable names, you just need a loop with an index...

This will do the job:

for i in {1..5} ; do echo $i"q;d" ; done

Tags:

Bash

Variable