本文介绍了Bash for循环设置变量,其值并对其进行评估?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何使用for循环来定义变量,和其值,和并能够对其求值?
How do I use a for loop to define a variable, and its value, and be able to evaluate it?
我无法弄清楚评估部分,但是使用for循环定义变量和似乎可行.具体来说,
I can't figure out the evaluation part, but using the for loop to define the variable and its value seems to work. Specifically,
for i in {1..4}
do
export my${i}var="./path${i}_tofile"
# or
# export my${i}var=./path${i}_tofile
# or
# eval "my${i}var=\"./path${i}_tofile\""
echo $[my${i}var]
done
echo
的计算结果不正确,但是外壳程序正确创建了变量和值.
The echo
does not evaluate correctly, but the shell does correctly create the variable and the value.
echo $my1var
返回
./path1_tofile
但是我需要使用$i
作为变量名称的一部分来评估变量.
But I need to evaluate the variables using the $i
as part of their names.
推荐答案
如果您不使用数组,这会变得很复杂:
This is how it gets complicated if you don't use an array:
for i in {1..4}
do
declare my${i}var="./path${i}_tofile"
tmpvar=my${i}var # temporary variabled needed for...
echo "$tmpvar=${!tmpvar}" # bash indirect variable expansion
done
这篇关于Bash for循环设置变量,其值并对其进行评估?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!