What if you could add error handling with just four characters per command? That's what this does. Prefix any command that could fail catastrophically with "try " with this little chunk of code at the top, and if you get a non-zero return code (i.e., the command failed), your script will terminate immediately with a semi-useful error messages showing you what failed.
Just put this little snippet at the top of your script:
Now, if you have a "cd" that might fail, stick a "try" in front of it. Instead of:======================================================== #!/bin/ksh yell() { echo "$0: $*" >&2; } die() { yell "$*"; rm -f /tmp/$$.*; exit 111; } try() { "$@" || die "cannot $*"; } ========================================================
do this:cd /smoedir rm -r *
gives you this output when run:yell() { echo "$0: $*" >&2; } die() { yell "$*"; rm -f /tmp/$$.*; exit 111; } try() { "$@" || die "cannot $*"; } try cd /smoedir rm -r *
the "rm" is never executed (thank goodness -- or at least, thank error checking).$ ksh test test[7]: cd: /smoedir - No such file or directory test: cannot cd /smoedir
As a result of the above, this often fails for remote execution via ssh.
There is an assumption that temp files created and not wanted to be left for examination of what went wrong are in the format $$.* -- process ID followed by a period then anything. This is a BAD WAY OF HANDLING TEMPORARY FILES unless your system lacks a real mktemp command. However, it's an easy way to handle temp files on quick and dirty scripts, but should not be used for "serious" projects.
This is not good error handling for serious projects or user-facing stuff. It does
not replace proper error handling -- it is a good way to add error handling to stuff
that otherwise wouldn't have got any.
Holland Consulting home
page
Contact Holland Consulting
since June 20, 2021
Page is Copyright 2020, Nick Holland, Holland Consulting. The Try/Yell/Die script is other people's work.