Home > Mobile >  Is there a bash function for determining number of variables from a read provided from end user
Is there a bash function for determining number of variables from a read provided from end user

Time:11-04

I am currently working on a small command line interface tool that someone not very familiar with bash could run from their computer. I have changed content for confidentiality, however functionality has remained the same.

The user would be given a prompt the user would then respond with their answer(s) From this, I would be given two bits of information:
1.their responses now as individual variables 2.the number of variables that I have now been given: this value is now a variable as well

my current script is as follows

echo List your favorite car manufacturers 
read $car1 $car2 $car3 #end user can list as many as they wish

for n in {1..$numberofmanufacturers} #finding the number of 
variables/manufactures is my second question

do
echo car$n
done

I am wanting to allow for the user to enter as many car manufacturers as they please (1=<n), however I need each manufacturer to be a different variable. I also need to be able to automate the count of the number of manufacturers and have that value be its own new variable.

Would I be better suited for having the end user create a .txt file in which they list (vertically) their manufactures, thus forcing me to use wc -l to determine the number of manufacturers?

I appreciate any help in advance.

CodePudding user response:

As I said in the comment, whenever you want to use multiple dynamically created variables, you should check if there isn't a better data structure for your use case; and in almost all cases there will be. Here is the implementation using bash arrays. It prints out the contents of the input array in three different ways.

echo List your favorite car manufacturers 
# read in an array, split on spaces
read -a cars


echo Looping over array values
for car in "${cars[@]}"
do
  echo $car
done

echo Looping over array indices
for i in ${!cars[@]}
do
  echo ${cars[$i]}
done

echo Looping from 0 to length-1
let numcars=${#cars[@]}
for i in $(seq 0 $((numcars-1)))
do
  echo ${cars[$i]}
done
  • Related