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? 

4 Answers 4

9
 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 
Sign up to request clarification or add additional context in comments.

2 Comments

I tried this on cygwin and linux, but it didn't work. It works if you remove the backticks: eval echo '$'$var_name
this is a more general solution than the "printenv" one, which only applies to environment variables
2

printenv is not a ksh builtin and may not always be present. For older ksh versions, prior to ksh93, the eval 'expression' method works best.

A powerful method in ksh93 is to use indirection variables with 'nameref' or 'typeset -n'.

Define and verify a nameref variable that refers to $PATH:

$ nameref indirect=PATH $ print $indirect /usr/bin:/usr/sbin 

See how the nameref variable changes when we change PATH:

$ PATH=/usr/bin:/usr/sbin:/usr/local/bin $ print $indirect /usr/bin:/usr/sbin:/usr/local/bin 

Show ksh version and the alias for nameref:

$ type nameref nameref is an alias for 'typeset -n' $ echo ${.sh.version} Version JM 93t+ 2010-02-02 

Comments

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

1 Comment

printenv will only work for exported variables. Normal shell variables will not appear empty. I would recommend @Kevin's answer instead, if ksh is old, and does not support nameref.
0

For one step above your answer (I spent a lot of time trying to find both these answers). The below will allow you to export a dynamic variable and then recall it dynamically:

echo -n "Please provide short name for path:" read PATH_SHORTCUT echo -n "Please provide path:" read PATH eval export \${PATH_SHORTCUT}_PATH="${PATH}" eval echo Path shortcut: ${PATH_SHORTCUT} set to \$"${PATH_SHORTCUT}_PATH". 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.