How To Ideas | How To Articles | How To Tutorials


0

How to find Average of Numbers provided through Command Line using Shell Script


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:

  1. 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.
  2. Find sum of all the numbers provided and store the result in variable total.
  3. Now divide the variable total by number of arguments supplied which is the average of numbers provided.

Instructions:

  1. Tell the Terminal to use bash as shell to execute the script using following line of code.
    #!/bin/bash
  2. Now create three variables total, average and number. total variable to store sum of all the numbers, average to store average of all the numbers and number to store total number of arguments supplied. Initialize total and average to 0 and number to number of arguments supplied.
    total=0
    average=0
    number=$#
  3. 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
  4. 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
  5. Now find average by dividing the variable total by variable number and finally print the result.
    average=`expr $total / $number`
    echo "Average of all the numbers is $average"

Here are some screenshots of the sample code.

Find Average Using Shell Script

Find Average Using Shell Script

Find Average Using Shell Script

Find Average Using Shell Script

Find Average Using Shell Script

Find Average Using Shell Script

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)
Filed in: Shell Scripting Tags: , , , , , , , , , ,

Leave a Reply

Submit Comment



© 9610 How To Ideas. All rights reserved.
Proudly designed by Theme Junkie.