Thursday, June 16, 2011

Example of getopts and HEREDOC in shell script

#!/bin/sh
prog=`basename $0`

usage () {
        msg=$1
        cat <<EOT
usage: $prog [-h][-y][-r <message>]

$msg

EOT

#
# handle options here
#
reportFlag=0
yesFlag=0
reportMessage='none'
while getopts 'hr:y' OPTION
do
        case $OPTION in
        h)      helpFlag=1
                ;;
        r)      reportFlag=1
                reportMessage="$OPTARG"
                ;;
        y)      yesFlag=1
                ;;
        ?)      usage "Unknown arg [$NAME]" ; exit 1; shift;
                ;;
        esac
done

shift $(($OPTIND - 1))

if [ "$helpFlag" ]
then
        usage "Help called."
        exit 0
fi

cat <<EOT

The report flag is $reportFlag and reportMessage is "$reportMessage".
The yes flag is $yesFlag.

EOT

No comments:

Post a Comment