Exceptions in the Shell

Writing scripts in bash has many advantages (and disadvantages) over writing them in Python or Ruby, but does leave us missing a few nice-to-haves (but you don’t have to change language to get them).

These nice-to-haves that are often missing in bash inspired the simbol project: a self-contained bash scripting framework which provides functionality to make bash scripts easier to write, easier to read, more maintainable and more usable.

One such nice-to-have missing in bash is stack traces. Sure, you can always bash -x a processes to see what went wrong, but that’s not as useful as an actual stack trace.

So, without further ado, some sample code:

New dummy function

New dummy function

Here I’ve hijacked the util module temporarily to demonstrate how to use the core:raise() function. Note that new function util:jest() expects 3 arguments, and raises an exception otherwise.  Now, executing this function (via simbol, without providing 3 arguments), simbol’s core:raise() function is triggered, as follows:

Resulting bash exception

Resulting bash exception

While this looks like a traditional exception handling stack trace, it isn’t true exception handling:  the core:raise() function acts similar to Python’s raise statement, or Ruby’s raise method from the Kernel module, but there is no exception handling as such; you can’t catch such an exception here.

Internally, the core:raise() function is a hack (but a nicely abstracted hack), using BASH_LINENO, BASH_SOURCE and FUNCNAME to work out what went wrong, and where.  The rest is mechanical, and you can examine it for yourself in the source (grep for core:raise()).

The simbol project is currently a work in progress, and there’s a lot of ground to cover in making bash code much easier to read, write and maintain. If you have any suggestions, tweet them to @obsecurious.

About Nima Talebi

Joke with the jesters, tickle the trolls, banter with the bards.
This entry was posted in Computers, Jesting and tagged , , , , . Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s