Make Bash Shell Safe with “set -euxo pipefail”

Linux Bash provides the scripting capabilities which is very familiar with programming languages. By using the Bash shell complex applications can be developed. For example, years ago a lot of CGI web applications are developed with the Linux Bash scripting language. But while developing bash scripts there are a lot of pitfalls because it is not a complete programming language and provides a lot of empty areas. To prevent unexpected errors the bash set should be configured as safe by using some shell environment variables.

set -e

When multiple lines of the script are executed if one of the lines fails the executive resumes with the next line. This may be a problem in some cases because the execution of the failed line may affect other lines. By using the set -e command if a line of the bash script fails the execution is stopped and exits from the current script.

set -e

set -u

The set -u command is very similar to the set -e where the variables are not used with errors. If a variable gets an error the script exits immediately.

set -u

set -f

The globbing is a very useful feature. But if your script has some incompatibilities about globbing use the set -f command. This command disables filename expansion also known as globbing.

set -f

set -o pipefail

Piping is one of the most powerful features of bash scripting. By default, if one of the commands in the pipe fails the pipe continues to execute. But this can be a problem for failsafe bash scripts. So the set -o pipefail command can be used to exit execution if one of the commands in the pipe fails.

set -o pipefail

set -euxo pipefail

Up to now we have listed some commands and options in order to make a bash script failsafe from different situations. All of these commands and options can be executed as a single command like below which makes the bash script failsafe.

set -euxo pipefail

Leave a Comment