Bash Tricks: Create variables dynamically using some eval magic

There are times when you are writing a script and you have the name of a variable as a variable and the desired value as another variable. Now you want to declare the stored name as a variable and assign the stored value to it. This is how you do it.


eval ${variableName}=`echo -ne \""${variableVal}"\"`

echo $test #"test" variable created dynamically using eval

What the script does is, it creates a variable with a name same as the string(“test”) stored in $variableName, and assigns it the value equal to the one stored in $variableVal(“123”).