2

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

#!/bin/sh

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

How can I get this done in perl/bash?

1
  • 3
    Please be so polite to read the two minute help→tour to get familiar with this Q&A site. Especially the part about no chit-chat (click on the "edited .. ago" link to see what was removed as inappropriate in your post).
    – Anthon
    Commented Apr 4, 2015 at 5:21

2 Answers 2

5

man 1 bash says:

If the first character of parameter is an exclamation point (!), it introduces a level of variable indirection. Bash uses the value of the variable formed from the rest of parameter as the name of the variable; this variable is then expanded and that value is used in the rest of the substitution, rather than the value of parameter itself. This is known as indirect expansion.

$ server1=abc,def,ghc
$ HOSTNAME=server1
$ echo ${!HOSTNAME}
abc,def,ghc
1

In bash:

$ server1=abc,def,ghc
$ HOSTNAME=server1
$ eval "echo \$$HOSTNAME"
abc,def,ghc

In Perl (no using strict):

$server1 = "abc,def,ghc";
$HOSTNAME = "server1";
print "$$HOSTNAME\n";

Both variants are not really nice and cross many borders of clean scripting.

Not the answer you're looking for? Browse other questions tagged .