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.

Property

server1=abc,def,ghc
server2=xyz,tes,iuy


echo $server1
abc,def,ghc

echo $HOSTNAME
server1

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

echo $$HOSTNAME
$server1

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

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:

${!HOSTNAME}

e.g.

echo ${!HOSTNAME}

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

       ${!prefix*}
              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.