Wednesday, July 17, 2013

This script takes integer numbers as command line arguments and displays their sum on the screen if run with no arguments, it informs user with usage message

#!/bin/bash
#######################################################
# File Name     :    sy_3_g
# Author:    :    Suresh Yadagiri
# Date        :    July 27,2010
# Descriptiom    :   
#  This script takes integer numbers as command line
#  arguments and displays their sum on the screen    
#  if run with no arguments, it informs user
#  with usage message
#
######################################################

printusageinfo(){
    echo "Usage: $0 number-list"
    exit 1
}
function is_integer() {
    printf "%d" $1 > /dev/null 2>&1
    return $?
}

if [ $# = 0 ]
then
    echo "Usage: $0 number-list"
    exit 1
fi

sum=0 #Running sum initialized to zero
count=0 #To count number of arguments

while [ $# != 0 ]
do
if is_integer $1; then
     # "$1 is an integer"
    sum=`expr $sum + $1`
    count=`expr $count + 1`
    shift # Shift the counted number out
else
        echo "$1 is not an integer"
    printusageinfo   
fi

done

#displaying final sum

echo "The sum of given $count numbers is $sum."
exit 0

No comments:

Post a Comment