Bash script settings

This is part of the Semicolon&Sons Code Diary - consisting of lessons learned on the job. You're in the unix category.

Last Updated: 2024-11-21

You should nearly always set -u in shell scripts.

This is equivalent to set -o nounset in long-hand form

In most programming languages, you get an error if you try to use an unset variable. But not in Bash - by default, unset variables are evaluated as empty string. The result of this is

rm -rf "$DIRECTORY/*"

will actually run rm -rf /* if $DIRECTORY is unset and would destroy your system. However, if instead you use set -u, bash will stop and fail on unset variables.

How to trace a bash script and see commands run

set -x # or set -o xtrace

bash will now print out every command it runs before running it. This is obviously a godsend for debugging. The most common way to use this is via the triggering of an ENV var

if [[ "${TRACE-0}" == "1" ]]; then # If TRACE is set to 1, this will print the commands as they are executed. Helps with debugging.
    set -o xtrace
fi

How to exit if any command fails

By default, the script fill keep going even if a command fails

set -e
# or set -o errexit

AND

set -o pipefail

ensure that a pipeline command is treated as failed, even if one command in the pipeline fails.

Resources