Average of given numbers in Bash


Program to compute average in bash.

Examples:

Input :  1 2 3 4 5
Output : average : 3.0

Input :  1 2 3 4 10
Output : average : 5.0

Program to compute average is simple. It is also called as Mean.
Formula:



 
(sum of all elements) / (total no. of elements)

The extension for bash programs end with .sh. Elements are stored in array which are traversed in while loop to calculate the sum. It is recommended to understand Arrays in Shell.
The avg is caculated using bc command. bc command is used for command line calculator.
Programs in bash is executed as follows :

sh program_name.sh
     OR
./program_name.sh
filter_none

edit
close

play_arrow

link
brightness_4
code

# Total numbers
n=5
   
# copying the value of n
m=$n
   
# initialized sum by 0
sum=0
   
# array initialized with
# some numbers
array=(1 2 3 4 5)
   
# loop until n is greater
# than 0
while [ $n -gt 0 ]
do
    # copy element in a 
    # temp variable
    num=${array[`expr $n - 1`]}    
   
    # add them to sum
    sum=`expr $sum + $num`
   
    # decrement count of n
    n=`expr $n - 1`
done
   
# displaying the average 
# by piping with bc command
# bc is bash calculator
# command
avg=`echo "$sum / $m" | bc -l`
printf '%0.3f' "$avg"

chevron_right


Output :

3.0


My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.




Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.