Better bash script

It’s really important to catch errors as soon as they occur and to fail fast. Nothing can be worse than continuing with something like:

mv ${FILE_NAME} ${DST_DIR}

Notice how the variable name FILE_NAME or DST_DIR is still undefined.

To handle such scenarios, it’s important to use set builtins like set -o errexitset -o pipefail, or set -o nounset at the start of the script. This ensures your script exits as soon as it encounters any nonzero exit code, usage of undefined variables, failed piped commands, etc.

#!/bin/sh

set -o errexit
set -o nounset
set -o pipefail

cp ${FILE_NAME} ${DST_DIR}

echo "continue..."

Output:

./ppp.sh: line 7: FILE_NAME: unbound variable

Note: Builtins like set -o errexit however will exit the script as soon as a ‘non-handled’ return code (othen than zero) comes up.