Stop getting burned by the shell script set -e trap

Shell Scripting & Automation

Stop getting burned by the shell script set -e trap

Technical Briefing | 9/17/2026

Every sysadmin eventually learns to start their scripts with set -e to stop execution the moment a command fails. It feels like a safe default until you realize it doesn’t work the way you think it does. I have seen countless production deployments get halfway through a risky configuration change because a command inside a pipe or a conditional block silently ignored the exit status of its predecessor. It is a classic foot-gun that most tutorials ignore.

Pipes and logical operators are where it breaks

The set -e flag only triggers when the last command in a pipeline returns a non-zero exit code. If you have something like grep or a transformation script in the middle, the shell keeps right on chugging if that middle command fails. It is infuriating when you are piping logs into a processor and the filter dies, but the script carries on as if everything is fine. You need to be explicit about handling failures in those cases.

set -eo pipefail
command_that_might_fail | grep pattern > output.txt

  • Pipefail is the missing piece that forces the shell to care about the exit status of every single command in a chain.
  • Conditional statements like if command then do not trigger the -e behavior, even if the command inside dies.
  • Subshells behave differently than the main script, so local error handling inside functions is still required.

The only way to be sure

If you are running anything that touches state, like database migrations or config generation, stop relying on global settings. Use || exit 1 after sensitive commands to be crystal clear about your intentions. It adds noise to your code, but it beats explaining to your boss why the automation wiped half the directory because the shell didn’t think the error was important enough to stop for. When in doubt, check the exit code yourself.

Linux Admin Automation  |  © www.ngelinux.com  |  9/17/2026

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Newest
Oldest Most Voted