Operating System - HP-UX
1826422 Members
3790 Online
109692 Solutions
New Discussion

nested variables (or dynamic variables)

 
SOLVED
Go to solution
Vishwa
Occasional Advisor

nested variables (or dynamic variables)


How do we create a dynamic variable on korn shell ?. Or to put it in other words how do we reference a variable using values from other variables ?

For example, I want to refer the variable $XY using value of $a (X) and a constant value Y.

a=X
XY=test

abc=${${X}Y}} # This did not work...

any suggestions ?

- Vi
When going gets tough, upgrade. © Murphy.
3 REPLIES 3
Vishwa
Occasional Advisor

Re: nested variables (or dynamic variables)

sorry the script should be..

abc=${${a}Y}

I get an error 'bad substitution'...

When going gets tough, upgrade. © Murphy.
Santosh Nair_1
Honored Contributor

Re: nested variables (or dynamic variables)

I'm sure there's a better way to do it, but how about this:

#!/bin/sh

a=X
XY=test
abc=$(eval echo \$${a}Y)

echo $a:$XY:$abc


-Santosh
Life is what's happening while you're busy making other plans
John Palmer
Honored Contributor
Solution

Re: nested variables (or dynamic variables)

eval is the way to go - it tells the shell to parse the line again.

a=X
XY=test
eval abc=\${${a}Y}

print $abc
test

This works as follows:
on the first pass the shell does parameter substitution of ${a} and ends up with
eval abc=${XY}

eval forces a second parameter substitution and you end up with
abc=test

Regards,
John