在echo之前扩展变量内的变量
例子:
testing="test"
var=""${testing} the variable""
testing="Update"
echo "$var"
输出:测试变量
所需输出:更新变量
回答
使用字符串时会扩展变量,它们不是记住变量替换的模板。
如果需要这样做,则需要将变量逐字地放入字符串中,并使用eval.
testing="test"
var='"${testing} the variable"'
testing="Update"
eval "echo $var"
但是eval很危险——它会执行字符串中的任何 shell 命令。更好的解决方案可能是使用某种占位符字符串并使用 shell 扩展运算符替换它。
var='#testing# the variable'
testing="Update"
echo "${var//#testing#/$testing}"