Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/shell/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Unix 灰分变量间接参考_Unix_Shell - Fatal编程技术网

Unix 灰分变量间接参考

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

我试图将一个脚本从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 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)”之后想到的