Unix 灰分变量间接参考
我试图将一个脚本从BASH移植到ASH(almquistshell),但遇到了间接引用的问题。以下函数Unix 灰分变量间接参考,unix,shell,Unix,Shell,我试图将一个脚本从BASH移植到ASH(almquistshell),但遇到了间接引用的问题。以下函数 cmd() { # first argument is the index to print (ie label) arg=$1 # ditch the first argument shift # print the label (via indirect reference) echo "${!arg}" } 应产生以下输出 cmd 1 o
cmd() {
# first argument is the index to print (ie label)
arg=$1
# ditch the first argument
shift
# print the label (via indirect reference)
echo "${!arg}"
}
应产生以下输出
cmd 1 one two three
one
cmd 2 one two three
two
cmd 3 one two three
three
这在BASH下可以正常工作,但在ASH(或DASH)下运行时会生成“语法错误:错误替换”。这样行吗?如果没有,是否有使用间接引用的替代方法?您可以尝试
eval
:
cmd() {
arg=$1
shift
eval "echo \$$arg"
}
这几乎正是我在发布echo“$(eval echo\$$arg)”之后想到的