#!/bin/bash
# This example shows how to calculate the sum and the
# product of the command line parameters. A variable
# number of parameters are allowed.
#
# One function calculates the sum while the other
# calculates the product.
calc_total()
{
tot=0
numargs=$# # "$#" holds argument count
for ((i=1; i<=$numargs; i++))
do
((tot += $1))
shift # shift/remove first argument
done
return $tot
}
calc_prod()
{
prod=1
numargs=$#
for ((i=1; i<=$numargs; i++))
do
((prod *= $1))
shift
done
return $prod
}
calc_total $@ # call summation function
echo 'Sum (with $?) is:' $? # returned result is "$?"
echo 'Sum (with $tot) is:' $tot # We can peek into $tot if not redefined
echo
calc_prod $@ # calculate product with all cmd-line args
echo 'Product (with $?) is:' $? # largest return value is 256
echo 'Product (with $prod) is:' $prod # but we can peek at the real number