Writing BASH Scripts


This document collects basic syntax and best practices for writing BASH scripts.

Starting scripts

It is good practice to start BASH scripts with the following lines:


set -euo pipefail


The command set allows you to change shell options. The most useful flags are:

Stop execution when an error is encountered. You can “catch” an error to prevent the shell from exiting by appending || true after a failing command.
-o pipefail
Catch errors in pipes. Return zero exit status only if all commands in a pipeline succeed.
Error out when shell encounters undefined variables by their values.
Debug mode. Prints every line and output, substituting variables
Disable file globbing.