alwaysInBeta Stable software is for the weak

Shell script safety net date: 2014-10-26 04:10:01+00:00 categories: - Linux - Programming tags: - shell

First the meat:

` !/bin/sh set -x set -e ”`

Now an explanation.

Every shell script starts with something like #!/bin/bash or #!/usr/bin/env sh or #!/usr/bin/bash #for those who only care about Arch linux;)

But what's the next line? If you're writing a hacked-together script that does exactly one thing because you want to do the same thing on 5 (or 50) boxes but don't want to make a general purpose solution, you should make sure that the script will stop if something goes wrong instead of digging itself a deeper hole. The solution is the these two shell options:

I've tested this successfully in Bash, Dash, zsh, and sh, so I'm pretty confident that it's portable to Bourne-like shells in general. UPDATE: Better yet; POSIX actually specs these options on set.

For reference:

[brian@charizard ~]$ cat

#for testing:

set -x
set -e
echo hello
echo $?
notARealCommand || echo caught
echo goodbye

[brian@charizard ~]$ ./
+ set -e
+ echo hello
+ echo 0
+ notARealCommand
./ line 12: notARealCommand: command not found
+ echo caught
+ uncaughtFakeCommand
./ line 13: uncaughtFakeCommand: command not found