unix - ASH 变量间接引用

标签 unix shell

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

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"
}

关于unix - ASH 变量间接引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1014522/

相关文章:

linux - 将前 100 个正则表达式匹配的文件名复制到 unix 中的另一个目录

unix - 拖尾多个文件并grep输出

linux - bash shell 脚本中的模函数

linux - 给定列表中最新编辑的文件 SHELL

Bash 参数扩展 - 获取文件的直接父目录

linux - 从 bash 脚本启动 Node 脚本

windows - 为什么 sort 命令在法语语言环境中对 "œ"和 "oe"进行无差别排序?

java - 奇怪的 File.list() 行为

php - 为什么 php 脚本变慢了?

linux - 更改/etc/profile 后,我需要做什么来重置我的 shell?