0
0
Bash-scriptingHow-ToBeginner · 3 min read

How to Use set -e in Bash for Error Handling

Use set -e in a bash script to make the script stop running immediately if any command returns a non-zero exit status. This helps catch errors early and prevents the script from continuing with unexpected states.
📐

Syntax

The set command changes shell behavior. Using set -e tells bash to exit the script if any command fails (returns a non-zero exit code). This is useful for stopping scripts on errors automatically.

  • set: command to change shell options
  • -e: option to exit on any error
bash
set -e
💻

Example

This example shows a script with set -e. It stops running when a command fails, so the last echo does not run.

bash
#!/bin/bash
set -e

echo "Start script"
false  # This command fails with exit code 1

echo "This line will not run"
Output
Start script
⚠️

Common Pitfalls

Some commands returning non-zero exit codes are expected and not errors, like grep when no match is found. Using set -e blindly can stop scripts unexpectedly.

To avoid this, you can:

  • Use command || true to ignore errors for specific commands.
  • Use if statements to handle expected failures.
bash
# Wrong way: script stops unexpectedly
set -e

if grep "text" file.txt; then
  echo "Found text"
fi

# Right way: ignore grep failure
set -e

grep "text" file.txt || true
 echo "Script continues even if grep fails"
Output
Script continues even if grep fails
📊

Quick Reference

OptionDescription
set -eExit script if any command fails
command || trueIgnore error of a specific command
if command; then ... fiHandle command failure explicitly

Key Takeaways

Use set -e to make bash scripts stop on any command failure automatically.
set -e helps catch errors early and prevents running commands after failures.
Some commands may fail normally; use || true or if statements to handle them.
Always test scripts with set -e to understand where they might stop.
set -e improves script reliability by avoiding hidden errors.