Diary of a geek

November 2009
Mon Tue Wed Thu Fri Sat Sun

Andrew Pollock


Other people's blogs


RSS feed

Contact me

JavaScript required

Friday, 20 November 2009

"#!/bin/sh -e" considered harmful

Russell Coker advocates putting -e on the shebang line of shell scripts.

I disagree. From my experience this is extremely unhelpful to people who may be debugging your shell scripts in the future.

Consider this, you've added -e to the shebang of a script, and some poor schmuck down the track is trying to debug why it spontaneously exits. What's the most obvious way to do this? Run the script with sh -x or bash -x.

What happens when you do this? The shebang is completely ignored, and the script is directly run by the shell interpreter. If the person doing the debugging doesn't happen to transpose all of the shell options on the shebang line to the manual shell interpreter invocation, you're going to get different behaviour.

So I advocate an explicit set -e on the second line of shell scripts instead.

As much as making shell scripts set -e is a good practice, it drives me absolutely batty having to deal with scripts that spontaneously exit as soon as something they run exits non-zero. Particularly when you've chained a bunch of shell scripts together, or have one sourcing a bunch of script fragments from a directory. For this reason, I prefer to write in Bash and use an exit handler, to make it very obvious when a shell script has abended due to set -e.

[10:04] [tech] [permalink]