We all write Bash scripts. They are convenient, fast and powerful. But how to make them safer?
Bash provides some simple options that you can set at the beginning of every script (unless you have a good reason not to) that will keep things a little safer by causing the script to exit when unexpected stuff happens.
These options are configured with the set
option that you can read all about here.
The options you should set are the following:
set -euo pipefail
Put this at the beginning of your script under the interpreter line e.g.:
#! /usr/bin/env bash
set -euo pipefail
The options mean as follows:
-e
- Exit immediately if any command fails.-u
- Exit if an unset variable is invoked.-o pipefail
- Exit if a command in a piped series of commands fails.
Setting this in your scripts will help stop them doing anything unintended.