Nandakumar Edamana
Share on:
@ R t f

Shell Script to Find the Average of Numbers Received via Command Line


Programs can take input via the command line instead of prompting the user after the program starts execution. Most standard command line tools do this. Modern programs can also support command line input. For example, you can use the command firefox en.wikipedia.org to launch Firefox with the English Wikipedia.

The following code illustrates how you can implement the support for command line arguments. This is a program that prints the average of the given numbers. It is of course a silly program. However, please read carefully as this code tells you how to handle command line arguments.

Code

#!/bin/sh

sum=0
count=$#

if [ $count -lt 1 ]; then
	echo "ERROR: No numbers given. Please give some numbers as command line arguments."
	exit 1
fi

while [ -n "$1" ]; do
	sum=$(expr $sum + $1)
	shift # Now $1 points to the next number (arg, actually).
done

avg=$(echo "scale=4; $sum / $count"|bc)

echo "The average of given $count numbers is $avg"

Execution

This program takes the input as command line arguments. For example, if you would like to find the average of 10, 20 and 25, you should call the script like this:

sh SCRIPTNAME.sh 10 20 25

or

chmod +x SCRIPTNAME.sh
./SCRIPTNAME.sh 10 20 25

Please don't forget to substitute SCRIPTNAME with the actual title.


Keywords (click to browse): average command-line arguments cli shell sh bash linux gnu unix script programming