Reputation: 21
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
Upvotes: 2
Views: 606
Reputation: 7791
You're almost there. Just use an array and populate it inside the loop.
#!/usr/bin/env bash
values=()
for i in {1..3}; do
read -p "Insert value $i: " v
values+=("$v")
printf '%s %s\n' "you wrote" "$v"
done
echo
echo "check of saved values:"
echo ${values[0]}
echo ${values[1]}
echo ${values[2]}
Just keep in mind that bash arrays are starts from zero 0
index.
EDIT: As pointed out by Ivan, the zero indexed array can be change according to the value of the for loop.
#!/usr/bin/env bash
values=()
for i in {1..3}; do
read -p "Insert value $i: " v
values[$i]="$v"
printf '%s %s\n' "you wrote" "$v"
done
echo
echo "check of saved values:"
echo ${values[1]}
echo ${values[2]}
echo ${values[3]}
Upvotes: 1
Reputation: 531035
As pointed out, you need indirect variable expansion. However, you can also use an array to group related values. v[$i]
is a valid name for read
.
for i in {1..3}
do
read -p "Insert value $i: " "v[$i]"
echo "you wrote ${v[$i]}"
done
echo
echo "check of saved values:"
echo "${v[1]}"
echo "${v[2]}"
echo "${v[3]}"
Upvotes: 3
Reputation: 7277
Also works with printf
for i in {1..3}; {
varname=v$i
read -p "Insert value $i: " value
printf -v $varname "$value"
echo "you wrote $value"
}
echo
echo "check of saved values:"
echo $v1
echo $v2
echo $v3
Upvotes: 2
Reputation: 2544
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
Upvotes: 3