echo $HOSTNAME result become key to a variable

Diana Sy asked:

Can someone please help me with a bash script? Can’t seem to wrap my mind aoround it.



echo $server1


with those info above, I want to output the output “abc,def,ghc” in a test variable.

echo \$$HOSTNAME

bash-4.1$ test=`echo \$$HOSTNAME`
bash-4.1$ echo $test

If someone can pls help me get this done in perl/bash or any code I can use pls. Thank you.

My answer:

You’re looking for:



echo ${!HOSTNAME}

This is generally known as a nested variable. The bash man page explains how this construct works:

              Names matching prefix. Expands to the names of variables whose
              names begin with prefix, separated by the first character of the
              IFS special variable.

But, beware in this particular circumstance, because $HOSTNAME generally contains the hostname of the computer, which is supposed to be a fully qualified domain name, and these contain dots, which are not valid in bash variable names.

View the full question and answer on Server Fault.

Creative Commons License
This work is licensed under a Creative Commons Attribution-ShareAlike 3.0 Unported License.