linux poison RSS
linux poison Email

Bash Script : Iterate over command line arguments

Below is simple bash script to calculate the average of integer numbers passed to the script from the command line arguments.

$#  - give the value of total number of argument passed to the script
$@ - using this we can  Iterate over command line arguments.

$ cat average.sh
#!/bin/bash

SUM=0
AVERAGE=0
ARG=$#
for var in "$@"; do
        if [ "$var" -eq "$var" 2>/dev/null ]; then
                if (( "$var" == 0 || "$var" > 100 )); then
                        echo "Invalid entry (ignored): $var"
                        ARG=$(($ARG-1))
                else
                        SUM=$(($SUM+$var))
                fi
        else
                echo "Invalid entry (ignored): $var"
                ARG=$(($ARG-1))
        fi
done
echo
AVERAGE=$(($SUM/$ARG))
echo "Average is : $AVERAGE"
echo

Output: 
$./average.sh 2 2 3.4 2 2 4.5 1001 0
Invalid entry (ignored): 3.4
Invalid entry (ignored): 4.5
Invalid entry (ignored): 1001
Invalid entry (ignored): 0

Average is : 2


Feel free to modify or use this script.



4 comments:

Anonymous said...

Why is 3.4 being ignored??

Unknown said...

because 3.4 is not an integer, if you want to work with the float values change this script to ksh.

Unknown said...

Run the script with arguments: 2 010
Result is: Average is : 5
But it should be 6.
-----
Problem: bash handles numbers (even on input) having leading 0's as octal.
Solution: use bash's base 10 arithmetic:
SUM=$(($SUM+$((10#$var))))
Now with input: 2 010
Result is: Average is : 6
-----
This is a gotcha all bash scripters must trap when processing user input.

Unknown said...

Thanks for this wonderful infomation.

Post a Comment

Related Posts with Thumbnails