BASH

Robust Bash Scripting: Error Handling and Exit Traps

Enhance Bash script reliability with `set -e`, `set -u`, `set -o pipefail` for strict error management and `trap` for guaranteed cleanup on script exit.

#!/bin/bash

# Exit immediately if a command exits with a non-zero status.
set -e

# Treat unset variables as an error.
set -u

# If a command in a pipeline fails, that return code will be used.
set -o pipefail

# Function to perform cleanup actions
cleanup() {
  echo "Cleaning up temporary files..."
  if [ -f "$TEMP_FILE" ]; then
    rm -f "$TEMP_FILE"
  fi
  echo "Cleanup complete."
}

# Register the cleanup function to run on EXIT or ERR signals
trap cleanup EXIT
trap cleanup ERR

# --- Script Logic Starts Here ---

TEMP_FILE="/tmp/myscript_temp_$(date +%s).txt"

echo "Creating temporary file: $TEMP_FILE"
touch "$TEMP_FILE"

# Simulate a command that might fail
echo "Running a potentially failing command..."
# This command will cause set -e to exit, triggering the ERR trap and then EXIT trap
ls -l non_existent_directory

echo "This line will not be reached if previous command fails."

# Simulate a successful completion scenario
echo "Script completed successfully."

# If the script finishes without error, 'cleanup' will still be called via EXIT trap
How it works: `set -e` makes the script exit immediately if any command fails. `set -u` treats unset variables as an error, preventing subtle bugs. `set -o pipefail` ensures that a pipeline's exit status is that of the rightmost command that exited with a non-zero status. The `trap` command allows you to execute commands when specific signals are received (e.g., `EXIT` when the script finishes, `ERR` when an error occurs). This is crucial for ensuring resources like temporary files are cleaned up reliably, even if the script terminates unexpectedly.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs