variable expansion and prevention (65 Views)
Reply
Trusted Contributor
Glenn S. Davidson
Posts: 221
Registered: ‎06-04-1997
Message 1 of 3 (65 Views)
Accepted Solution

variable expansion and prevention

I have spent a few hrs on this and I think I need to start asking questions. I haven't found any information on this.

I want to be able to use a variable name as a variable value in the same script. Like this:

mary=lamb
peter=pumpkin
for i in mary peter
do
echo "$i has the last name of ${$i}"
done

No, this doesn't work but the output should look like this:

mary has the last name of lamb
peter has the last name of pumpkin

I can easily do this in perl with a hash but I need to do it in a shell script (sh or ksh) if it's possible.

I've tried a miriad of ways and I'm hoping someone can assist me with it.
Conformity Destroys a mans initiative and independence. It supresses his powerful inner drive to do his own thing.
Please use plain text.
Acclaimed Contributor
James R. Ferguson
Posts: 21,184
Registered: ‎07-06-2000
Message 2 of 3 (65 Views)

Re: variable expansion and prevention

hi Glenn:

#!/usr/bin/sh
mary=lamb
peter=pumpkin
for i in mary peter
do
eval echo "$i has the last name of \${$i}"
done

...yields:

mary has the last name of lamb
peter has the last name of pumpkin

Regards!

...JRF...
Please use plain text.
Trusted Contributor
Glenn S. Davidson
Posts: 221
Registered: ‎06-04-1997
Message 3 of 3 (65 Views)

Re: variable expansion and prevention

SWEET!!!!

I bet I tried every other possible combination.

Thanks a bunch!
Conformity Destroys a mans initiative and independence. It supresses his powerful inner drive to do his own thing.
Please use plain text.
The opinions expressed above are the personal opinions of the authors, not of HP. By using this site, you accept the Terms of Use and Rules of Participation