Languages and Scripting
Showing results for 
Search instead for 
Do you mean 

variable expansion and prevention

SOLVED
Go to Solution
Trusted Contributor Trusted Contributor

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.
2 REPLIES
Acclaimed Contributor Acclaimed Contributor

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...
Highlighted
Trusted Contributor Trusted Contributor

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.