[Date Prev][Date Next] [Thread Prev][Thread Next] [Date Index] [Thread Index]

Re: bash question: reporting a variable named within a variable



Corey Hickey wrote:

> I'm writing a bash script wherein I have a list of variables of which I
> want to return the values. A script representative of what I am trying
> to do would be like this:
> 
> 
> #!/bin/bash
> 
> FOO=bar
> BLAH=blarg
> 
> for var in FOO BLAH ; do
> 	echo $var = $"$var" #this part is messed up
> done
> #end
> 
> 
> The script above returns:
> 
> FOO = FOO
> BLAH = BLAH
> 
> ...but what I want it to return is
> 
> FOO = bar
> BLAH = blarg
> 
> so obviously I need to change the $"$var" to something else, but I'm at
> a loss as to what. I've tried various combinations of quotes, dollar
> signs, curly braces, backticks, and pounding myself on the head, but to
> no avail. :)

    echo $var=$(eval echo \$$var)

seems to do the trick. You need to escape the first $ to prevent $$
being mistaken for the "current process ID" variable, and you need eval
to force the variable name to be re-evaluated after the initial
substitution.

Craig

Attachment: pgpKCSHo1foZA.pgp
Description: PGP signature


Reply to: