0

I am learning bash, and wanted to do something very simple, here's my script:

#!/bin/bash

#read-multiple: reads multiple values from keyboard

echo -n "Enter one or more values:"
read var1 var2 var3 var4 var5

for i in {1..5}
do
    echo var$i= ${var"$i"}
done

In the for loop I am trying to print to values entered by the user, only at the echoline I get the error:

${var"$i"}: bad substitution 

What I was expecting to happen is:

  1. $i expands to the current value between 1 and 5 (say 1 for example)
  2. ${var"$i"} expands to ${var1} which expands to the value of var1

This is not the case apparently...Could you explain to me why that is ? does bash expand everything on the line at once?

I have also tried ${var${$i}} and $var${$i} but both give the same error...why is that ?

codeforester
  • 39,467
  • 16
  • 112
  • 140
ColdCoffeeMug
  • 168
  • 1
  • 13

1 Answers1

4

You could do this:

for v in var{1..5}; do
  echo $v = ${!v}
done

or

for i in {1..5}; do
  v="var$i"
  echo $v = ${!v}
done

See this post:

Documentation here:

codeforester
  • 39,467
  • 16
  • 112
  • 140
  • What I want to do is actually use the `var1, var2...` isn't there a way o use the value of `$i` in the naming of the variable I would use at each loop iteration ? – ColdCoffeeMug Oct 18 '17 at 18:01