LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)
-   -   create variable name in bash (https://www.linuxquestions.org/questions/programming-9/create-variable-name-in-bash-397577/)

kilgor 12-29-2005 10:04 AM

create variable name in bash
 
Hi,

I have a bash script which takes it's configuration options from another file.

The options are variables like:
Code:

abc_hello=1
abc_byebye=0
xyz_dog=4
xyz_tree=7

etc

Point being, the name consists of two or more parts.

The script loads the conf file:

Code:

. /path/to/config.conf
Now it has these variables,
Code:

echo $xyz_tree
will return 7 and so on.

Problem is, there are many variables and they change but are systematic. The script can actually generate names like abc_hello correctly from other settings in the config file and then, hopefully, use them in loops.

How can I force the generated name to act as a variable?

For example:
Code:

hello_world=10

one=hello
two=world

Now I want to echo the result "10" using "$one" and "$two".
Code:

echo "$"$one"_"$two""
produces '$hello_world', but I need the value of $hello_world which would be '10'.

Is it possible at all with bash 2? I have tried various combinations but haven't had any luck. I hope I'm just missing some kind of bash trick.


Thanks.

Hko 12-29-2005 11:27 AM

Quote:

I hope I'm just missing some kind of bash trick.
Fortunately, you are. :)
Code:

#!/bin/bash

hello_world=10

one=hello
two=world

varname=${one}_${two}  # Combining the two names to one
varvalue=${!varname}  # Here's the trick

echo $varvalue


kilgor 12-29-2005 11:59 AM

Quote:

Originally Posted by Hko
Here's the trick

Thank you very very much. That'll save me quite a few headaches.

eddiebaby1023 12-31-2005 10:50 AM

The bourne shell compatible way to do it is with eval:
Code:

eval varvalue=$varname


All times are GMT -5. The time now is 08:48 AM.