Reputation: 3747
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?
Upvotes: 2
Views: 10288
Reputation: 174
var_name=$1 #pretend here that the user passed the string "PATH"
printenv $var_name
Upvotes: 1
Reputation: 1
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".
Upvotes: 0
Reputation: 8456
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
Upvotes: 2
Reputation: 2390
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
Upvotes: 9