How can the trap command be used to handle signals in a bash script?

QuestionsQuestions8 SkillsProBash Trap CommandNov, 02 2025
087

You can use the trap command in a Bash script to handle signals by specifying the signal you want to catch and the command or function to execute when that signal is received. Here’s a basic example:

#!/bin/bash

# Define a cleanup function
cleanup() {
    echo "Cleaning up before exit..."
    # Add any cleanup commands here
    exit 0
}

# Set up the trap to catch SIGINT (Ctrl+C) and SIGTERM
trap cleanup SIGINT SIGTERM

# Main script logic
echo "Running script. Press Ctrl+C to interrupt."
while true; do
    sleep 1
done

Explanation:

  1. Cleanup Function: The cleanup function is defined to perform any necessary cleanup actions before the script exits.
  2. Trap Command: The trap command is set to call the cleanup function when either the SIGINT or SIGTERM signal is received.
  3. Main Logic: The script enters an infinite loop, simulating ongoing work. If you press Ctrl+C, the cleanup function will be executed, allowing for graceful termination.

You can customize the cleanup function to include any commands needed for your specific use case.

0 Comments

no data
Be the first to share your comment!