![一个变量嵌套在另一个变量中](https://linux22.com/image/183252/%E4%B8%80%E4%B8%AA%E5%8F%98%E9%87%8F%E5%B5%8C%E5%A5%97%E5%9C%A8%E5%8F%A6%E4%B8%80%E4%B8%AA%E5%8F%98%E9%87%8F%E4%B8%AD.png)
我有这些变量
a1=0.017
a2=0.2
a3=10.7
a4=20.9
a5=35.4
for ((x=1; x<=5; x++))
do
for i in a${x}
do
echo "Welcome $i times"
done
done
输出必须是:
"Welcome 0.017 times"
"Welcome 0.2 times"
"Welcome 10.7 times"
"Welcome 20.9 times"
"Welcome 35.4 times"
但我现在的输出是
Welcome a1 times
Welcome a2 times
Welcome a3 times
Welcome a4 times
Welcome a5 times
我如何以“10”的方式将 a1 打印为 $a1 ?
否则我必须这样做:
for i in $a1 $a2 $a3 $a4 $a5
do
echo "Welcome $i times"
done
问题是我有超过 100 个“a”变量,我无法使用上面的最后一个选项
“循环”之外的新建议也很好
非常感谢
答案1
完成你的要求并不难:
a1=0.017
a2=0.2
a3=10.7
a4=20.9
a5=35.4
for ((x = 1; x <= 5; x++)); do
var="a${x}"
echo "Welcome ${!var} times"
done
a
不过,创建一个数组变量会更简单:
a=(
0.017
0.2
10.7
20.9
35.4
)
for x in "${a[@]}"; do
echo "Welcome ${x} times"
done