ProbableOdyssey | Blake Cook

Understanding `set -euxo pipefail` in Bash Scripts

· 2 min read · 338 words

Many bash scripts you’ll see in the wild often have some variation of set -euxo pipefail at the top of the file. These settings make your scripts fail loudly and early when something goes wrong

I’m constantly looking this up whenever I come across it, so here are my quick notes for us to refer back to if/when we need a quick refresher.

set -e (Exit on Error)

The set -e option instructs Bash to immediately exit if any command (excluding certain contexts like while or if conditions, or the right-hand side of a pipeline) returns a non-zero exit status.

Bash will continue even if a command fails. set -e brings Bash closer to the behavior of other languages, ensuring that a failing command stops the script right away.

set -u (Unset Variables are Errors)

When set -u is active, referencing any variable that hasn’t been previously defined (with exceptions for $* and $@) will cause the script to immediately exit with an error.

By default, Bash silently uses an empty string for the unset/mistyped variables. This flag prevents common typos from creating new, empty variables without you realizing it.

set -x (Print Commands)

This option enables trace mode, printing each command’s expanded form to standard error immediately before it is executed. set -x helps you visualize the flow of your script by showing exactly which commands are being run and with what arguments.

set -o pipefail (Fail on Pipeline Errors)

By default, the exit status of a pipeline (command1 | command2) is the exit status of the last command, even if an earlier command in the pipeline failed. set -o pipefail changes this, ensuring that the entire pipeline’s exit status is that of the first non-zero exit status encountered.

This flag prevents errors in the middle of a pipeline from being silently ignored. For instance, if grep fails to find a file but pipes its (empty) output to sort, sort will succeed, and the pipeline would report success. With pipefail, the pipeline would correctly report grep’s failure.

Reply to this post by email blZake@proZbableodyssey.blog (remove Z characters) ↪