#!/bin/sh # append -x to above to debug this script # Illustrates: error handling and primitive argument handling. # Strip alphabetics or nonalphabetics from (contents of) files. usage() { ## via echos exec >&2 echo "Usage: `basename $0` -d|-k [file ...]" echo " -d delete alphabetic characters" echo " -k keep only alphabetic characters and spaces" echo " file... files to process" ## via here document. "-" strips off leading tabs cat >&2 <<-EOF Usage: `basename $0` -d|-k [file ...] -d delete alphabetic characters -k keep only alphabetic characters and spaces file... files to process EOF } if [ $# = 0 ] ; then echo >&2 "`basename $0`: option required" usage ; exit 1 fi case $1 in ## not very good - better to use "getopts" -d) opt=d ;; -k) opt=k ;; *) echo >&2 "`basename $0`: illegal option -- $1"; usage ; exit 1 ;; esac shift TMPFILE=/tmp/`basename $0`.$LOGNAME.$$ ## Simple signal handling example (also see "man kill"): trap 'echo "Trap 0." ; /bin/rm "$TMPFILE" 2>/dev/null' 0 trap 'echo "Trap 1,2,15." ; /bin/rm "$TMPFILE" 2>/dev/null; exit 1' 1 2 15 ## Signals: 1=hangup 2=interrupt(^C) 3=quit(^\) 15=kill ## Instead of terminating immediately, we clean up first. ## Signal 3 not used so as to give an escape hatch. ## To ignore signal 2: trap '' 2 ## To reset to default: trap 2 echo 'Sleeping for 5 seconds - try a signal if you wish.' ; sleep 5 echo Woke up MV="echo +++ mv " ## Defang this script while testing. # MV=mv ## What to use in the final production version! for i do if [ ! -f $i ] ; then echo >&2 "`basename $0`: file $i does not exist" elif [ $opt = d ] ; then tr -d '[:alpha:]' < $i > $TMPFILE && $MV $TMPFILE $i else tr -cd '[:alpha:]\n' < $i > $TMPFILE && $MV $TMPFILE $i fi done