Tips For Robust Bash Scripts

Here are a couple of quick tips for writing more robust shell scripts from my last 10 years of working with bash.

Tip 1: Use "set -e"

This will cause your script to exit if an error occurs.

#! /bin/sh
set -e
 
false ;# ops! exit here

If errors are OK, you can add "|| true" so that it'll continue.

#! /bin/sh
set -e
 
false || true ;# this is OK

Tip 2: Use "set -eu"

This means your script will exit if variables are not set, example:

echo $FOO ;# ops, $FOO not defined

You can provide defaults...

echo ${FOO:-'default'} ;# this is OK

Tip 3: Quote All Strings

You never know when an empty string will sneak in and break your script.

% F=""
% if [ $F == "" ] ; then echo "F is blank"; fi
-bash: [: ==: unary operator expected

Tip 4: Consider "find/while" Rather Than "for/find"

This is tolerant to spaces; and it's faster. This paradigm can be used is similar scenarios.

bad
% for F in $(find . -type f) ; do echo $F; done
...
./win
file.txt
...

good
% find . -type f | while read F ; do echo $F ; done
...
./win file.txt

If you enjoyed this post, perhaps you'd enjoy this post on robust cron-jobs.