Bash

另一個變數中的一個變數

  • November 11, 2020

我有這些變數

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”變數,我不能使用上面的最後一個選項

“循環”之外的新建議也很好嗎

非常感謝

完成您的要求並不難:

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

引用自:https://unix.stackexchange.com/questions/619088