Bash: Dynamically named variables

Bash: Dynamically named variables

Sometimes you want to run a series of commands that are slightly different, but for each command the arguments must also be slightly different. Say, for example, you have a script that runs multiple other commands and you want to give each one a temporary file to put its results in, then combine these at the end.
For this, you may want to use Dynamically Named Variables, variables whose names are determined programmatically.

Creating A Dynamic Variable

for ((i=0; i<${numberofvariables}; ++i)); do
    declare var${i}="${i}"

The above code will create variables named var0 to var4 containing the numbers 0 to 4.
The declare keyword there is important otherwise Bash tries to interpret it as a command, so this makes it clear that we want this to be a variable.

Using A Dynamic Variable

# One at a time...
echo "${var0}"
echo "${var1}"
# etc.
# Programmatically...
for ((i=0; i<${mumberofvariables}; ++i)); do
    echo "${!normalvar}"

Using a dynamic variable when knowing which one you want is easy,  but if you stored file names in these variables and wanted to join them all together, you’ll need to be able to use them programmatically as well.
Here, a normal variable is used to allow Bash to properly evaluate the dynamic variable name for this iteration of the loop.
The ! after the opening braces tells Bash to use the contents of the normal variable as the real variable name.


No Comments

Add your comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.