One of the more difficult parts of scripting is error handling. It really isn't fun, but if you forget to verify the return code of a "cd" command, you could end up doing an rm -r * in the wrong place. That's bad, of course.

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:


yell() { echo "$0: $*" >&2; }
die() { yell "$*"; rm -f /tmp/$$.*; exit 111; }
try() { "$@" || die "cannot $*"; }
Now, if you have a "cd" that might fail, stick a "try" in front of it. Instead of:
cd /smoedir
rm -r *
do this:
yell() { echo "$0: $*" >&2; }
die() { yell "$*"; rm -f /tmp/$$.*; exit 111; }
try() { "$@" || die "cannot $*"; }

try cd /smoedir
rm -r *
gives you this output when run:
$ ksh test
test[7]: cd: /smoedir - No such file or directory
test: cannot cd /smoedir
the "rm" is never executed (thank goodness -- or at least, thank error checking).

How it works:

"try" is a function defined in the three magic lines. It executes the command, and IF IT FAILS, executes the "die" function, which deletes temp files in the format /tmp/$$.* (named based on the process ID of the running script. It then echos the failed command exactly as it was tried to be executed, and exits.


Any command that is dependent upon quotes being correct will probably fail unless you perfectly handle escaping the quotes. I'd recommend manually handling errors rather than trying to quote everything so "try" works as intended.

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.