Tell me more ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems.. It's 100% free, no registration required.

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

share|improve this question
Note that you can't have spaces around the = sign in an assignment. I took the liberty of fixing your code since this isn't what the question is about. – Gilles Jun 23 '12 at 0:16
The technical term is variable indirection. – Thor Jun 24 '12 at 13:18
thank you @Gilles. That was in fact a typo – Brandon Kreisel Jun 25 '12 at 12:48

2 Answers

up vote 5 down vote accepted

You can do this sort of thing 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.

share|improve this answer

In ksh93 (and recent enough versions of mksh and bash), you can write

echo ${!myvar}

Zsh requires ${(P)myvar} instead.

In older shells, including ksh88 and pdksh, your only recourse is to use eval, as explained by Bruce Ediger.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.