Search code examples
linuxbashnumbersaverage

Bash - Calculate the Average of Numbers Inputted


Need help with Linux Bash script. Essentially, when run the script asks for three sets of numbers from the user and then calculates the numbers inputted and finds the average.

#!/bin/bash

echo "Enter a number: "
read a
   while [ "$a" = $ ]; do

echo "Enter a second set of numbers: "
read b
b=$
   if [ b=$ ]

Am I going about this wrong?


Solution

  • Still not sure what you want a to be. But I think you can just loop 3 times. Then each iteration get a set of numbers, and add them up and keep track of how many you have. So something like below. (note $numbers and $sum are initialized to 0 automatically)

    #!/bin/bash    
    sum=0
    numbers=0
    for a in {1..3}; do
      read -p $'Enter a set of numbers:\n' b
      for j in $b; do
        [[ $j =~ ^[0-9]+$ ]] || { echo "$j is not a number" >&2 && exit 1; } 
        ((numbers+=1)) && ((sum+=j))
      done
    done
    
    ((numbers==0)) && avg=0 || avg=$(echo "$sum / $numbers" | bc -l)
    echo "Sum of inputs = $sum"
    echo "Number of inputs = $numbers"
    printf "Average input = %.2f\n" $avg                               
    

    Where example output would be

    Enter a set of numbers: 
    1 2 3
    Enter a set of numbers: 
    1 2 3
    Enter a set of numbers: 
    7
    Sum of inputs = 19
    Number of inputs = 7
    Average input = 2.71