BASH

Robust Error Handling and Exit Strategy in Bash

Implement a robust error handling strategy in Bash scripts using `set -e`, `trap`, and custom error messages, ensuring reliable execution and proper cleanup.

#!/bin/bash

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

# Keep track of the last executed command, if we're in debug mode.
# trap 'last_command=$current_command; current_command=$BASH_COMMAND' DEBUG

# Function to be called on EXIT, ERR, INT, TERM signals
cleanup() {
    echo "Performing cleanup operations..."
    # Add your cleanup commands here, e.g., removing temporary files
    # rm -f /tmp/myapp_temp_file.txt
    echo "Cleanup complete."
}

# Trap signals for robust exit handling
trap cleanup EXIT     # Always run cleanup when script exits
trap 'echo "ERROR: A command failed. Script will exit."; cleanup; exit 1' ERR # Run cleanup and exit with error on command failure
trap 'echo "WARNING: Script interrupted by Ctrl+C. Exiting."; cleanup; exit 1' INT # Handle Ctrl+C
trap 'echo "WARNING: Script terminated. Exiting."; cleanup; exit 1' TERM # Handle kill signal

log_message() {
    local type=$1
    local message=$2
    echo "[$(date +'%Y-%m-%d %H:%M:%S')] [$type] $message"
}

log_message INFO "Starting script execution."

# Simulate some operations
log_message INFO "Attempting operation 1..."
sleep 1
# Example of a command that might fail (uncomment to test error handling)
# ls /nonexistent_directory
log_message INFO "Operation 1 successful."

log_message INFO "Attempting operation 2..."
sleep 1
# Example of a command that will succeed
echo "Hello from script." > /tmp/temp_output.txt
log_message INFO "Operation 2 successful."

# Simulate a graceful exit
log_message INFO "Script finished successfully."
exit 0
How it works: This snippet provides a robust error handling and exit strategy for Bash scripts. `set -e` ensures the script exits immediately if any command fails. `trap` is used to execute the `cleanup` function on specific signals like `EXIT` (always), `ERR` (on command failure), `INT` (Ctrl+C), and `TERM` (termination signal). This ensures that critical cleanup operations, like removing temporary files, are always performed, enhancing script reliability and preventing orphaned resources.

Need help integrating this into your project?

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

Hire DigitalCodeLabs