#!/bin/sh # # General pattern for testing if a command worked and bailing # out if it didn't. # NOTE: 'echo' is *not* portable, revise subroutines below when moving # from system to system. #============================================================================== # Subroutines =============================================================== #============================================================================== info () # $1 = informational message to STDERR # Send an informational message to STDERR { /bin/echo "% `basename $0`: $1" >&2; } #------------------------------------------------------------------------------ warn () # $1 = integer error code; $2 = message to STDERR # Send a warning message to STDERR { /bin/echo "? `basename $0` ($1): $2" >&2; } #------------------------------------------------------------------------------ die () # $1 = integer exit code; $2 = message to STDERR # Send an error message to STDERR and abort script with provided exit code. { /bin/echo -e "! `basename $0` ($1): $2\n_ $0 script aborted" >&2; exit $1; } #============================================================================== # Main Line ================================================================= #============================================================================== #-------------------------------+ # Test and note if the command | # worked or not. | #-------------------------------+ echo "Test 1"; info "Test 1a"; if (rm sample.dat) then warn $? 'rm sample.dat worked'; else warn $? 'rm sample.dat failed'; fi; if (rm -f sample.dat) # rm -f never fails. then warn $? 'rm sample.dat worked'; else warn $? 'rm sample.dat failed'; fi; #-------------------------------+ # Single step approaches. | # Remember "0" is true and any | # other value is false. | #-------------------------------+ echo "Test 2"; #---------------------------------------+ # Suceed or die. | #---------------------------------------+ man man > delete.me || die $? 'unable to create sample input data'; #---------------------------------------+ # Null step if OK else error case. | #---------------------------------------+ if (man man > delete.me) then : else die $? 'unable to create sample input data'; fi; #---------------------------------------+ # Capture return code and test for non- | # OK status. | #---------------------------------------+ mv delete.me sample.data; exitStat=$?; if [ $exitStat -ne 0 ] then die $exitStat 'unable to rename file'; fi; #---------------------------------------+ # Use for-each loop as a block for | # cascading tests, sort of like a DCL | # ON WARNING THEN construct. | #---------------------------------------+ for blockOK in false; do # Initially set flag to false. man man >delete.me || break; mv delete.me sample.dat || break; rm sample.dat || break; blockOK=true done; if [ "$blockOK" = "true" ] then info 'we made it'; else die 1 "we didn't make it"; fi; #==[ EOF: ok-or-die ]==