I'm attempting to take user input using a for
loop and bash's read
utility. (Using bash version 5.0.17) As there are multiple inputs, I am using the i
iterator to differentiate each input that is entered. That part works as I can echo
the variable.
What I have not figured out, is how to access those variables, dynamically, in another loop. What I had in mind was to use the num
variable again in the second loop because I need to loop the same amount of times to bring the data in and output the data later. I was thinking that I can just use the i
iterator again, as an index, that would concatenate to the string and I would be able to access the variable. However that is not so.
What I've tried:
- If I use
echo "$str$i"
that will not work because the variable "str" does not exist. Therefore the out put was just0
and1
- I tried using a string str and tried to concat it with the variable
$i
;echo "str$i"
but that just gave me the outputstr0
andstr1
- I also had a few string literal attempts but that was messy.
Lines 10 and 11 echo $str0
and echo $str1
show me that those variable are created and accessible because I get the output qwe
and asd
. So how would I loop through to access each of those variables so that the output of the second loop is also qwe
and asd
?
Please see the code below and the resulting output below that:
#!/bin/bash
read -p "How many variables to loop?: " num
for (( i=0; i<num; i++ ))
do
read -p "Enter no. $[i+1] string: " str$i
done
# assuming you enter at least two
echo $str0
echo $str1
echo ++++++++++++++++++++
# I would like to loop through however many entries were entered above
# but I cannot figure out how to do this.
for (( i=0; i<num; i++ ))
do
echo "$str$i"
# echo "str$i"
done
$ ./concat.sh
How many variables to loop?: 2
Enter no. 1 string: qwe
Enter no. 2 string: asd
qwe
asd
++++++++++++++++++++
0
1
I did look into an array solution but my brain is fried from working on the above. If an array is the way to go, lemme know! Thanks in advance!