BASH

Handling Signals and Graceful Script Termination with trap

Learn to use the `trap` command in bash to intercept signals like Ctrl+C (SIGINT), allowing scripts to perform cleanup tasks and exit gracefully.

#!/bin/bash
# Demonstrates graceful exit using 'trap' for cleanup operations

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

# Function to perform cleanup
cleanup() {
  echo -e "
Caught SIGINT or SIGTERM. Performing cleanup..."
  if [ -f "$TEMP_FILE" ]; then
    rm "$TEMP_FILE"
    echo "Removed temporary file: $TEMP_FILE"
  fi
  echo "Exiting gracefully."
  exit 0 # Exit with success after cleanup
}

# Set up traps for SIGINT (Ctrl+C) and SIGTERM
trap cleanup SIGINT SIGTERM

echo "Script started. Creating a temporary file: $TEMP_FILE"
echo "Some temporary data" > "$TEMP_FILE"
echo "Press Ctrl+C to stop and trigger cleanup."
echo "Script will run indefinitely until interrupted."

# Simulate a long-running process
while true; do
  sleep 1
  echo -n "."
done
How it works: This script showcases how to use the `trap` command to intercept system signals like `SIGINT` (generated by Ctrl+C) and `SIGTERM`. When such a signal is received, instead of immediately terminating, the script executes a `cleanup` function. This function can be used to remove temporary files, stop child processes, or save state, ensuring a graceful exit and preventing resource leaks in long-running web-related scripts.

Need help integrating this into your project?

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

Hire DigitalCodeLabs