本文介绍了ASH变量间接引用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将脚本从 BASH 移植到 ASH (Almquist SHell),但遇到了间接引用问题.下面的函数

I'm trying to port a script from BASH to ASH (Almquist SHell) and am running into a problem with indirect references. The following function

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)下运行时会生成语法错误:替换错误".这应该工作吗?如果没有,是否有使用间接引用的替代方法?

This works as expected under BASH, but generates a "syntax error: Bad substitution" when run under ASH (or DASH). Should this work? If not, is there an alternative to using indirect references?

推荐答案

你可以试试eval:

cmd() {
    arg=$1
    shift
    eval "echo \$$arg"
}

这篇关于ASH变量间接引用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-21 14:05