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:

Post a Comment

Related Posts with Thumbnails