Contents /
Previous /
Next
Functions
Function definitions provide a way to
group statement blocks into one:
#!/bin/sh
function usage ()
{
echo "Usage:"
echo " myprog.sh [--test|--help|--version]"
}
case $1 in
--test|-t)
echo "you used the --test option"
exit 0
;;
--help|-h)
usage
;;
--version|-v)
echo "myprog.sh version 0.0.2"
exit 0
;;
-*)
echo "Error: no such option $1"
usage
exit 1
;;
esac
echo "You typed \"$1\" on the command-line"
Here is a function to calculate factorials:
function factorial ()
{
N=$1
A=1
while test $N -gt 0 ; do
A=`expr $A '*' $N`
N=`expr $N - 1`
done
echo $A
}
You can now run factorial 20 and see the output.
To assign the output to a variable do: X=`factorial 20`.
Parameters to the function have the same names
as command-line parameters to the script.
Note the * in forward quotes to prevent the shell
from expanding it into matching file names.