linux - 动态创建 bash 变量并访问其先前定义的值

标签 linux bash shell scripting sh

我正在尝试读取之前定义的 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/

相关文章:

linux - 如何移植在2.6内核中编译的linux驱动程序,而不用在其他新版本内核中编译

java - "ant all"构建无法继续。 'Cannot run program "java ".'

php - 确保系统调用在所有先前的系统调用之后运行

linux - 忽略空行并执行 sdiff

linux - Bash If 语句 - 放弃希望

linux - 即使在 CAS 服务器中成功验证后也无法重定向到应用程序页面

linux - 如果命令 "cat/dev/net/tun"结果 $string 那么

linux - 如何同时打开三个终端(进程)

linux - 使用 shell 脚本压缩字典

php - 递归重命名文件名并转义特殊字符的 Shell 脚本?