当您获得变量名称时,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?
有帮助吗?

解决方案

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

其他提示

eval `echo '$'$var_name`

回声将'$'与$ var_name中的变量名称相连,评估对其进行评估以显示值。

编辑:以上不太正确。正确的答案是没有回头的。

eval echo '$'$var_name

printenv 不是KSH内置的,可能并不总是存在。对于较旧的ksh版本,之前 KSH93, ,评估“表达”方法最有效。

KSH93中的一种强大方法是使用“ nameref'或'facteet -n'的间接变量。

定义并验证 Nameref 引用的变量 $PATH:

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

看看如何 Nameref 当我们更改时可变变化 PATH:

$ 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

超过您的答案一步(我花了很多时间试图找到这两个答案)。以下将使您能够导出一个动态变量,然后动态回忆:

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".
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top