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:
-
set -x
will make the interpreter echo every command as it executes, fully expanded (inline variables, etc.) -
set -e
will make the interpreter halt the script if any line/command returns a non-zero exit code (i.e., if something goes wrong); if you expect a non-zero exit somewhere, just use || to catch it
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 testSafetyNet.sh
#!/bin/bash
#for testing:
#!/home/brian/.local/bin/sh
#!/usr/bin/dash
#!/usr/bin/zsh
set -x
set -e
echo hello
echo $?
notARealCommand || echo caught
uncaughtFakeCommand
echo goodbye
[brian@charizard ~]$ ./testSafetyNet.sh
+ set -e
+ echo hello
hello
+ echo 0
0
+ notARealCommand
./testsh.sh: line 12: notARealCommand: command not found
+ echo caught
caught
+ uncaughtFakeCommand
./testsh.sh: line 13: uncaughtFakeCommand: command not found