tags:

views:

238

answers:

2

Is there a way in ksh to get a variable's value when you have been given the name of the variable?

For example:

#!/usr/bin/ksh
var_name=$1  #pretend here that the user passed the string "PATH"
echo ${$var_name}  #echo value of $PATH -- what do I do here?
+2  A: 
eval `echo '$'$var_name`

echo concatenates a '$' to the variable name inside $var_name, eval evaluates it to show the value.

EDIT: The above isn't quite right. The correct answer is with no backticks.

eval echo '$'$var_name
Kevin Beck
I tried this on cygwin and linux, but it didn't work. It works if you remove the backticks:eval echo '$'$var_name
mtruesdell
Indeed. I have edited my answer to correct it.
Kevin Beck
this is a more general solution than the "printenv" one, which only applies to environment variables
Joe Watkins
+1  A: 

var_name=$1 #pretend here that the user passed the string "PATH"

printenv $var_name

shortbaldman
clean and simple, thank you!
mtruesdell

related questions