Back to Blog

Zsh Lesson20 Error Handling

Sandy LaneSandy Lane

Video: Zsh Lesson20 Error Handling by Taught by Celeste AI - AI Coding Coach

Watch full page →

Zsh Lesson20 Error Handling

Mastering error handling in Zsh is essential for writing robust shell scripts. This lesson explains how to interpret exit codes using $?, implement strict modes like set -euo pipefail, and use trap commands for cleanup and error detection.

Code

# Exit code demo: success (0) vs failure (non-zero)
ls /tmp       # likely succeeds
echo "Exit code: $?"  # prints 0 if success

ls /nope      # likely fails
echo "Exit code: $?"  # prints non-zero if failure

# Custom exit code
if [ ! -f /tmp/file ]; then
  echo "File missing, exiting with code 42"
  exit 42
fi

# Using if, ||, && to check commands
mkdir /tmp/mydir && echo "Created directory" || echo "Failed to create directory"

# Enable strict mode for safer scripts
set -euo pipefail

# -e: exit on any error
# -u: error on unset variables
# -o pipefail: fail if any command in a pipeline fails

# Trap for cleanup on script exit
cleanup() {
  echo "Cleaning up temporary files..."
  rm -rf /tmp/mytempdir
}
trap cleanup EXIT

# Trap for error detection with line number
error_handler() {
  echo "Error occurred at line $1"
}
trap 'error_handler $LINENO' ERR

# Example function that triggers an error
error_prone() {
  echo "This will fail:"
  ls /nonexistent
}
error_prone

Key Points

  • Exit codes indicate success (0) or failure (non-zero) and are accessed via $?.
  • Strict mode (set -euo pipefail) helps catch errors early and prevents silent failures.
  • trap commands allow running cleanup code on EXIT or handling errors on ERR signals.
  • Custom exit codes can signal specific failure reasons for better script diagnostics.
  • Combining strict mode with traps is a best practice for production-ready Zsh scripts.