Shell Script – Use a Variable Reference Inside Another Variable

kshshell-scriptvariable substitution

I'm sure it is relatively simple, I just don't know how to do it.

#!/usr/bin/ksh
set `iostat`
myvar=6

I want to something like echo ${$myvar} which i want interpreted as ${$myvar} -> ${6} -> value

Best Answer

You can do this with eval, built-in to many fine shells, including ksh:

#!/usr/bin/ksh
set $(iostat)
myvar=6
eval "echo \${$myvar}"

The trick is to double-quote the string you feed to eval so that $myvar gets substituted with "6", and to backslash the outer dollar-sign, so that eval gets a string "$6".

I got "%user" for the output, but I tried it on a multi-processor RHEL machine.

Related Question