Tuesday, March 10, 2015

Shell Script Report Skelton

Over the years I have written and re-written a skeleton of a shell script that provide a bunch of basic program like functionality for bourn shell (sh) scripts. Mostly I use this as a sort of wrapper for Cron and At job. It provides:
  • Simple command line argument parsing.
  • Help (-h argument).
  • E-mail the standard out as a report.

Skeleton Shell Script

#!/bin/sh
#
# Skeleton shell script
#
# As written the output is mailed to the person defined by the MAILTO line.
# This is primarily intended as a skeleton for cron jobs.
#
# Copyright (C) 2015, Ean Kingston, All rights reserved.
#

####################
# Configuration Variables - These should be customized
####################

MAILTO=${MAILTO:-me@example.com} ## CHANGE THIS
MYRPTTITLE="Skeleton Report" ## CHANGE THIS
WORKDIR="/tmp/"

####################
# Internal Variables - these should not need to be changed
####################
# If PATH is not set, set it to something sane
PATH=${PATH:-/sbin:/bin:/usr/sbin:/usr/bin:/usr/local/sbin:/usr/local/bin}
MYRPTFILE=${WORKDIR}${0%'.sh'}.$ # Temporary file for the report.

####################
# Support subroutines
####################

# Display Usage information for the script. This will need to be edited.
printhelp() {
cat <<EOT
Usage: $0 [-h] [-m={email}]
This is a skeleton shell script. This text should be replaced with usage
information for the completed script.
   -m Send the mail to an alternate address, blank for stdout.
   default is ${MAILTO}
   -h Display this help text.

EOT
}

####################
# Start of Main code
####################

#####
# Proess command line arguements
for ARG ; do
   case $ARG in
      -[mM]=*) MAILTO=${ARG#-[mM]=} ;;
      -[hH]) printhelp ; exit ;;
      *) echo Unexpected command line arguement $ARG. Stopping. >&2 ; exit 1 ;;
   esac
done

#####
# Take everything from stdout and put it in a report file
{

## PLACE SCRIPT BODY HERE

} > $MYRPTFILE

#####
# Send (or print) the report
if [ -n "$MAILTO" ] ; then
   mail -s "$MYRPTTITLE" "$MAILTO" < $MYRPTFILE
else
   cat $MYRPTFILE
fi

#####
# Cleanup temporary file(s)
rm $MYRPTFILE

No comments:

Post a Comment