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.

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

% 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.

Tags

ant (2)   antlr (1)   applet (1)   apsectj (1)   asm (1)   aspectj (1)   bdd (1)   blog (1)   cd (1)   coldfusion (2)   concurrency (4)   cucumber (1)   dashing (1)   docker (3)   drop-wizard (1)   drupal (1)   dsl (1)   gatling (1)   geb (1)   gist (13)   git (1)   graphite (1)   groovy (2)   hibernate (2)   ioc (1)   java (44)   java-8 (1)   java-fx (1)   jmeter (2)   jpa (2)   junit (5)   links (12)   maven (12)   middleman (2)   mocking (1)   mongodb (1)   oped (9)   os-x (1)   performance (4)   photos (1)   plaf (14)   ruby (3)   scala (1)   selenium (4)   software (10)   spring (5)   spring-mvc (1)   swing (15)   testing (17)   tips (4)   tomcat (3)   tuples (1)   tutorial (1)   unix (6)   vagrant (2)   web (4)   windows (1)