← Back to all snippets
BASH

Robust Bash Script Error Handling and Cleanup

Enhance Bash script reliability using 'set -e' for immediate exits on error and 'trap' for guaranteed resource cleanup, critical for stable deployment or build processes.

#!/bin/bash\n\n# Exit immediately if a command exits with a non-zero status.\nset -e\n\n# Define a temporary file path\nTEMP_FILE="/tmp/my_script_output_$$.log" # $$ is the process ID, making it unique\n\n# Function to clean up temporary files and resources\ncleanup() {\n  echo "Executing cleanup function..."\n  if [ -f "$TEMP_FILE" ]; then\n    rm -f "$TEMP_FILE"\n    echo "Removed temporary file: $TEMP_FILE"\n  fi\n  # Add other cleanup logic here, e.g., stopping services, reverting changes\n  echo "Cleanup complete."
}\n\n# Trap for various exit signals:\n# EXIT: Always runs when the script exits, regardless of success or failure.\n# ERR: Runs if a command exits with a non-zero status (error).\n# INT: Runs if the script is interrupted (e.g., Ctrl+C).\n# TERM: Runs if the script receives a termination signal.\ntrap cleanup EXIT\ntrap 'echo "Error detected. Exiting script."; exit 1' ERR\ntrap 'echo "Script interrupted. Exiting."; exit 1' INT TERM\n\necho "Starting script execution."\n\n# Example 1: Create a temporary file\necho "This is some temporary data." > "$TEMP_FILE"\necho "Temporary file created at $TEMP_FILE"\n\n# Example 2: Simulate a successful command\nls /tmp\n\n# Example 3: Simulate an operation that might fail (uncomment to test error handling)\n# non_existent_command_to_fail # This line will trigger the ERR trap and cleanup\n\necho "Script execution finished successfully."\n# The 'cleanup' function will automatically run due to the EXIT trap.
How it works: This snippet demonstrates robust error handling in Bash scripts. `set -e` ensures that the script will exit immediately if any command fails. The `cleanup` function defines actions to be performed before the script exits, such as removing temporary files. `trap cleanup EXIT` guarantees that the `cleanup` function is called every time the script exits, whether due to success, an error, or an interruption signal (like Ctrl+C). Additional `trap` commands for `ERR`, `INT`, and `TERM` allow specific actions or messages for different types of script termination, making scripts more reliable for web development tasks like deployments or automated builds.

Need help integrating this into your project?

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

Hire DigitalCodeLabs