[plug] What was that? (firewall breached?)

James Devenish devenish at guild.uwa.edu.au
Fri May 16 15:11:33 WST 2003


In message <3EC4646D.8050202 at postnewspapers.com.au>
on Fri, May 16, 2003 at 12:09:17PM +0800, Craig Ringer wrote:
> >>>Too bad the shell doesn't have anything like Python's try blocks.
[...]
> ...if it does in fact have such structures. I've never 
> seen them used in any shell scripting, nor heard mention of them before, 
> but if there's a facility like that available in common shells I'll be 
> glad to hear of it.
[...]
> So ... how do you do it, if it can be done?

Okay, let's consider the features of Python's try blocks...(I don't like
Python's, but I'll refer to those once since they were cited by name):

 - "specifies exception handlers and/or cleanup code
   for a group of statements" [1]
 - "if no except clause matches the exception, the search for an
   exception handler continues in the surrounding code..."
 - has two different forms: "try...except" and "try...finally"
 - the "try..except" searches for a handler that is "compatible
   with the exception".

For analogous solutions in shell scripts, note that:

 - obviously, some shells have more features than others,
 - the general solution in a shell script will be based on "shell stuff"
   rather than "exception objects or classes".  That is, the very basic
   inter-process communication such as standard input/error/output and
   process exit codes.

With most shells, you can construct a script that would behave
in this way:

 - executes a block of statements which could succeed entirely, or fail
   part-way through,
 - handles specific failures, such as return codes or programme output,
   via specific handlers ("except"-like blocks),
 - contains a catch-all error handler and/or a "finally"-like block,
 - allows unhandled errors to fall through to the parent shell,
 - includes an alarm handler in case one of the statements takes too
   long.

Expressions that you would find in such scripts include "set -e",
"trap" and "$?".

I suppose something that makes Linux stand out from other operating
systems is that many tools are written in C or perl and shell scripting
doesn't play a very visible role, apart from the /etc/init.d scripts,
perhaps. Some other operating systems (perhaps those that have had some
BSD heritage?) have a larger proportion of shell scripts, so you would
commonly see error handling and flow control of this nature. (I don't
know what SCO is like for you.)

[1] Python Reference Manual 2.2 (21 Dec 2001 -- out of date, I suppose).




More information about the plug mailing list