Last Updated: September 09, 2019
·
20.4K
· vintikjeny

Dynamic variable name in bash

Sometime you may need to make variable's name at the runtime (for example, if you need to choose one of predefined constants) by inserting variable in variable's name. For that cases you can use indirect references.
For example:

#!/bin/bash
foo_num=2
foo_name="I am foo"

bar_num=3
bar_name="I am bar"

elements=( foo bar )

for element in ${elements[@]}
do
    #dynamicly making variable name
    current_num=$element\_num
    current_name=$element\_name
    #getting values
    echo "Element name: ${!current_name}"
    echo "Element number: ${!current_num}"
    echo"---"
done

This script will produce output:

Element name: My name is foo
Element number: 2
---
Element name: My name is bar
Element number: 3
---