linux - Bourne Shell (bin/sh) 中的嵌套变量

标签 linux bash shell sh

我有一个具有嵌套值的变量。

x=hello
y=world
helloworld=monday

TEMP=$x$y 
echo "${!TEMP}"   # I get output "monday" which is required

这在 bash 中有效,但在普通 sh 中无效。当我使用 sh 运行相同的命令时,最后一行给出“Bad Substitution”。

如何使用 sh 获得相同的结果?由于某些原因,我无法将 shell 从 sh 更改为 bash,因此我必须使用 sh 来完成此操作。

最佳答案

因为 sh 不同于 bash difference-between-sh-and-bash . 但是您可以使用这种方式获取 helloworld 的内容,也许有一些更好的方法,但如果您只对解决方案感兴趣,那么这将为您提供您正在寻找的东西:)

#!/bin/sh
x=hello
y=world
helloworld=monday
TEMP=$x$y
TEMP_FINAL='eval "echo \$$TEMP"'
eval "$TEMP_FINAL"

enter image description here

关于linux - Bourne Shell (bin/sh) 中的嵌套变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57057709/

相关文章:

linux - 破管不再结束程序?

linux - 使用 Ghostscript 从 PDF 文件中删除 CropBox

regex - “查找”使用带变量的正则表达式

python 在启动树莓派时运行时将输出保存到文件

php - 如何从命令行执行 PHP 代码?

linux - 我们需要 EXPORT_SYMBOL 和头文件声明吗

linux - 通过 ssh 运行 bash 脚本以启动激活器后,Travis-ci 不会退出

linux - 在 Bash 中按数字文件名排序的文本文件

linux - 如何找到没有软链接(soft link)的目录?

json - 使用shell动态添加json对象中的键值对