what is wrong with "echo" line in my loop? It should echo value of v1 after 1st input, v2 after 2nd input and v3 after 3rd input. Instead it's just echoes $i. Why is it ignoring $v ? After loop is done, I do "manual check" of the saver variables and they apparently exist.
Script:
#!/bin/bash
for i in {1..3}
do
read -p "Insert value $i: " v$i
echo "you wrote " $v$i #I have problem in this line
done
echo
echo "check of saved values:"
echo $v1
echo $v2
echo $v3
Console output:
./input_2.sh
Insert value 1: what
you wrote 1 #output should be: you wrote what
Insert value 2: the
you wrote 2 #output should be: you wrote the
Insert value 3: hell
you wrote 3 #output should be: you wrote hell
check of saved values:
what
the
hell
Thanks
This line:
echo "you wrote " $v$i
Tries to write variable $v followed by $i.
What you need is to store the variable name into a variable and then use the ${!}, for example:
varname=v$i
echo "you wrote " ${!varname}
A good practice would be to use this variable name for the read operation as well:
#!/bin/bash
for i in {1..3}
do
varname=v$i
read -p "Insert value $i: " $varname
echo "you wrote " ${!varname}
done
echo
echo "check of saved values:"
echo $v1
echo $v2
echo $v3
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With