当您获得变量的名称时,ksh 中是否有办法获取变量的值?
例如:
#!/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?
当您获得变量的名称时,ksh 中是否有办法获取变量的值?
例如:
#!/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?
eval `echo '$'$var_name`
echo 将“$”连接到 $var_name 中的变量名,eval 对其进行评估以显示该值。
编辑:以上内容不太正确。正确答案是没有反引号。
eval echo '$'$var_name
printenv
不是 ksh 内置的,可能并不总是存在。对于较旧的 ksh 版本,在ksh93之前,eval 'expression' 方法效果最好。
ksh93 中一个强大的方法是使用带有“nameref”或“typeset -n”的间接变量。
定义并验证引用的nameref变量$PATH
:
$ nameref indirect=PATH
$ print $indirect
/usr/bin:/usr/sbin
看看我们改变时namerefPATH
变量是如何改变的:
$ PATH=/usr/bin:/usr/sbin:/usr/local/bin
$ print $indirect
/usr/bin:/usr/sbin:/usr/local/bin
显示 ksh 版本和别名nameref
:
$ type nameref
nameref is an alias for 'typeset -n'
$ echo ${.sh.version}
Version JM 93t+ 2010-02-02
var_name=$1 #pretend here that the user passed the string "PATH"
printenv $var_name
比你的答案高出一步(我花了很多时间试图找到这两个答案)。下面将允许您导出动态变量,然后动态调用它:
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".