Today, I Learned...

by Justin Campbell

< All

Put set -e in bash scripts to exit on error.

#!/bin/bash
cd directory
echo "Deleting everything in the current directory"
$ ./script.sh
./script.sh: line 3: cd: stuff: No such file or directory
Deleting everything in the current directory
$

Oh no!

You can use set -e near the top of your script, or simply append -e to the shebang:

#!/bin/bash -e
cd directory
echo "Deleting everything in the current directory"
$ ./script.sh
./script.sh: line 5: cd: stuff: No such file or directory

Much better.

Learned from the first episode of Destroy All Software by @garybernhardt.

April 1st, 2013