1

I have these variables

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

The output must be:

"Welcome 0.017 times"
"Welcome 0.2 times"
"Welcome 10.7 times"
"Welcome 20.9 times"
"Welcome 35.4 times"

But my output now is

Welcome a1 times
Welcome a2 times
Welcome a3 times
Welcome a4 times
Welcome a5 times

How cam I print a1 as $a1 in the way to have "10" ?

Otherwise I have to do this:

for i in $a1 $a2 $a3 $a4 $a5
do
 echo "Welcome $i times"
done

The problem is that I have more than 100 "a" variables and I can not use the last option above

Are good also new suggestion outside of "loops"

Many thanks

4
  • 1
    Is there a reason you're not putting the data in an a array? E.g. as a[0]=10.1; a[1]=20.5 etc... And then loop with for value in "${a[@]}"; do ...; done.
    – Kusalananda
    Nov 11, 2020 at 15:52
  • 1
    It depends what shell you are using - in bash, you could use indirection like echo "Welcome ${!i} times" - see for example Bash: Echo a variable whose name is the value of another variable Nov 11, 2020 at 15:54
  • Kusalananda: no, there is not, just I have hard time to use correctly an array ... how can I use an array inside a loop please?
    – Emma Athan
    Nov 11, 2020 at 15:54
  • steeldriver: ok, I will try! thanks
    – Emma Athan
    Nov 11, 2020 at 15:55

1 Answer 1

1

It’s not hard to accomplish what you asked for:

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

It would have been simpler to make a an array variable, though:

a=(
    0.017
    0.2
    10.7
    20.9
    35.4
)

for x in "${a[@]}"; do
    echo "Welcome ${x} times"
done

2
  • Many thanks! The second code, array, is perfect for me! Thank you guys !!!
    – Emma Athan
    Nov 11, 2020 at 16:10
  • @EmmaAthan if you found the answer useful, please consider accepting it so that others facing a similar issue may find it more easily.
    – AdminBee
    Nov 11, 2020 at 16:17

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .