Indirectly reference bash variable

If you know the name of a variable which contains a value of interest, you need indirect referencing to retrieve the value, this is how you do it.

#!/bin/bash

j=1 #variable containg a value
i=j #variable containing the name of the variable which holds the value
eval k=\$$i #k now contains the value of j which is 1
echo $k
j=2
k=${!i}  #another way of indirectly referencing
echo $k

About Pratik Sinha

Linux Nerd, Socialist, Atheist, Adventuristic, Nature Lover, Geeky.

Leave a Reply