Shell tips and tricks

Tom Buskey tom at buskey.name
Wed Oct 31 15:32:50 EDT 2007


On 10/31/07, VirginSnow at vfemail.net <VirginSnow at vfemail.net> wrote:

> (7) Shell options?  What are those?



There are 2.  getopt and getopts.  Here's some snippets

getopt:

#!/bin/ksh
PROG=$(basename $0)
usage () {
  echo "$PROG   # report which systems are not pingable"
  echo "$PROG -s        # send output to syslog"
  echo "$PROG -h        # this help"
}

set -- $(getopt hs $@ )
if [ $? != 0 ]
then
  usage
  exit 1
fi

for i in $@
do
  case $i in
    -h) usage; exit 0;;
    -s) HOST=$(uname -n)
        LOGGER='logger -p local0.notice'
        shift;;
    --) shift; break;;
  esac
done


And getopts:

#!/bin/sh
PROG=`basename $0`
usage () {
  echo "$PROG options:"
  echo "   -h           # this help"
  echo "   -f file      # source this file"
  echo "   -a           # display all graphs on screen"
  echo "   -l           # plot with lines instead of points"
  echo "   -p printer   # print to printer"
  echo "   -g file      # create file.png"
  echo "    You must do -a, -c, or -u with -p"
}
if [ $# -eq 0 ]
then
  usage
  exit 1
fi
while getopts acf:g:hlp:u  options
do
  case $options in
    a) UPTIMES=1
       CONNECTIONS=1
       ALL=1
       ;;
    h|\?) usage
          exit 1
          ;;
    l) POINTS=lines
       ;;
    p) PAUSE=''
       PRINTER=$OPTARG
       TERM=postscript
       ;;
    f) DATA=$OPTARG
       ;;
    g) PAUSE=''
       PRINTER=$OPTARG
       TERM=png
       ;;
  esac
done
shift `expr $OPTIND - 1`

I prefer getopts as I usually like to have arguments to my options.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.gnhlug.org/mailman/private/gnhlug-discuss/attachments/20071031/adc62d99/attachment.html 


More information about the gnhlug-discuss mailing list