0

This is what I have so far. How could I incorporate count to take the user input each time the loop completes and add them together and create and average of the inputs?

#!/bin/bash
#Variables
lower=1
middle=50
higher=100
notdone=true

while [ $notdone ]; do

#Pick a Number
echo "Please pick a number between 1 and 100: "
read input


#Loop until wiithin range
until [[ $input -ge $lower ]] && [[ $input -le $higher ]]; do
    echo "Number not in range. 
    Please pick a number between 1 and 100: "
    read input
done

echo "You picked $input"

if [[ $input -ge $middle ]]; then 
    echo "Your answer is in the top half"
    fi

if [[ $input -le $middle ]]; then
    echo "Your answer is in the top half"
    fi
done
  • So I’ve since added count=0 as a variable within the while loop and at the end I’m trying to add something along the lines of total=$(expr “$count” + “$input”). But I can’t seem to figure out how to update the count variable with the user input from the previous run through the loop. – Aaron Brown Apr 23 '18 at 01:53

1 Answers1

0

Replying to your comment to the question: You don't need $count until actually computing the average. Until then, it's enough to have

total=$(( total + input ))

This will add what the user inputted to the running total.

The average could then be calculated as $(( total / count )) (note, since the shell only does integer arithmetics, this would be an integer, see "How to do integer & float calculations, in bash or other languages/frameworks?").


Other things:

Your $notdone variable is set to the string true and you use it in while [ $notdone ]. Tests like these, on unquoted strings, are fragile, and your while loop condition is better written as

while [ "$notdone" = "true" ]

You should also consider quoting all other variable expansions in your code, for example

if [[ "$input" -ge "$middle" ]]; then

This is extra important in your input loop, otherwise you'll generate a syntax error by inputting something with a space in the middle.

Since you are using bash, the above may also be written

if (( input >= middle )); then

You also lack a way of exiting your main loop, and both echo's at the end says "Your answer is in the top half".

Kusalananda
  • 333,661