这是我的示例片段
text="Var 1 is ${one}, Var 2 is ${two}, Var 3 is ${three}"
for (( i=0 ; i<1 ; i++ ))
do
one="one"
two="two"
three="three"
echo "${text}"
done
回报
Var 1 is , Var 2 is , Var 3 is
如果我将代码更改为此,它会按预期工作:
text="Var 1 is ${one}, Var 2 is ${two}, Var 3 is ${three}"
for (( i=0 ; i<1 ; i++ ))
do
one="one"
two="two"
three="three"
echo "Var 1 is ${one}, Var 2 is ${two}, Var 3 is ${three}"
done
答案1
发生这种情况是因为在设置“text”变量时,所有其他变量都是空的,默认为空字符串“”。
尝试text
按照您的命令进行设置,并使用 (') 保存,而不是使用 (") 保存,这样 bash 就不会计算您的表达式,然后如果您这样做的话。
$ text='echo "var1 = $one var2 = $two"'
$ one=hi
$ two=bye
然后eval $text
会返回var1 = hi var2 = bye