In this tutorial, I will show you how to use Shell Script to find Average of any number of arguments (numbers) provided through Command Line. The script will find show an error if no argument is provided, otherwise it will find Average of numbers provided and prints its output on the Terminal.
Algorithm:
- Check if the numbers of arguments supplied are equal to 0 or not. If yes, print error message and exit the script, otherwise move to step 2.
- Find sum of all the numbers provided and store the result in variable
total. - Now divide the variable
totalby number of arguments supplied which is the average of numbers provided.
Instructions:
- Tell the Terminal to use
bashas shell to execute the script using following line of code.
#!/bin/bash
- Now create three variables
total,averageandnumber.totalvariable to store sum of all the numbers,averageto store average of all the numbers andnumberto store total number of arguments supplied. Initializetotalandaverageto 0 andnumberto number of arguments supplied.
total=0 average=0 number=$#
- Now check if number of arguments supplied are equal to 0 or not, if yes then print an error message and exit the program.
if [ $# -eq 0 ] then echo "Usage: $0" echo "At least one argument required" echo "Example $0 number1 number2 ..." exit 1 fi - Now using for loop, loop through all the variables provided and find sum of all the numbers supplied using the following code.
for temp in $* do total=`expr $total + $temp` done - Now find average by dividing the variable
totalby variablenumberand finally print the result.
average=`expr $total / $number` echo "Average of all the numbers is $average"
Here are some screenshots of the sample code.
You can download the sample script from here.
Incoming search terms:
- How can Chake Using Number Idea (1)
- shell script to find sum of all prime numbers between (1)
Related posts:
How To Find Sum of Two Numbers which are supplied as Command Line Arguments How To find out Biggest number among the three provided numbers through command line using Shell Scripting How to check for leap year in Shell Script How To reverse the digits of a number using Shell Scripting How To Find Sum of Sum of digits of a number using Shell Scripting


