我正在尝试读取之前定义的 bash 变量的值,但该变量名称是动态派生的。
这是我正在尝试执行的 bash 脚本
$ mythreshold=10
$ table=my
$ threshold="$table"threshold
$ echo $("$threshold")
mythreshold
但是当我尝试读取这个变量值时
$ echo $("$threshold")
-bash: mythreshold: command not found
但是我期待它打印
$ echo $("$threshold")
10
有没有办法让我完成这项工作,它应该打印上面定义的 mythreshold 变量的值
最佳答案
$()
是命令替换。它在内部运行命令并返回输出。变量名不是命令。
您可以$(echo "$threshold")
,但这只会取回mythreshold
。
您需要indirection为了你想要的。具体Evaluating indirect/reference variables .
作为一个例子,对于这个特定的情况:
echo "${!threshold}"
关于linux - 动态创建 bash 变量并访问其先前定义的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26936928/