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.
#!/bin/bash
variableName="test"
variableVal="123"
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”).
Thanks for this! took forever to find a simple straight forward example to do this!
There is no need to use echo. Single quotes will also work:
eval ${variableName}=’${variableVal}’
Thanks !!! Was thinking how the hell to avoid eval from parsing variableVal as the name of a command !