0

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 just 0 and 1
  • I tried using a string str and tried to concat it with the variable $i; echo "str$i" but that just gave me the output str0 and str1
  • 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!

bennettnw2
  • 131
  • 2
  • 5
  • You may consider using an array and `readarray` builtin (a synonym for `mapfile`) with `-n` option. – M. Nejat Aydin Aug 30 '20 at 00:51
  • Hello there, thanks so much for the suggestion. I found my answer here using an array: https://askubuntu.com/questions/29215/how-can-i-read-user-input-as-an-array-in-bash Thanks again! – bennettnw2 Aug 30 '20 at 02:01
  • The accepted answer in the link you gave is debatable and likely inefficient. It assumes each array element will contain a single word (that is, won't contain a blank character). – M. Nejat Aydin Aug 30 '20 at 03:31
  • The answer I used was the one with 4 upvotes. I implemented it with a for loop. I really just needed the syntax on how to put user input into an array. This is for a very small and simple script so performance is not a big deal. – bennettnw2 Aug 30 '20 at 14:53

0 Answers0