Bash & Shell Scripting (50 Qs)•Part 2: Core Architecture & Implementation (Mid-Level)
What does `set -euo pipefail` do and why should every production script start with it?
senior LevelCode ExamplePipesSystem Design
In Simple Words: The gold standard for defensive shell scripting:
-e(errexit): Exits immediately if any command exits with a non-zero status. Prevents scripts from continuing after catastrophic errors (e.g. failingcd /dirfollowed byrm -rf *!).-u(nounset): Treats unset/uninitialized variables as an error and exits immediately (preventsrm -rf "$UNSET_VAR/*"wiping out/).-o pipefail: In a pipeline (cmd1 | cmd2 | cmd3), the return code is normally the exit status of the last command.pipefailensures that if any command in the pipeline fails, the whole pipeline fails!- Optional:
set -xfor debugging (prints each command before executing).
bash
#!/usr/bin/env bash
set -euo pipefail
# Script will terminate instantly if any command or variable fails!