How to handle SIGINT in scripts?

QuestionsQuestions8 SkillsProBash Trap CommandNov, 01 2025
091

To handle SIGINT in scripts, you can use the trap command in a Bash script. This allows you to define a function that will be executed when the SIGINT signal is received (typically when you press Ctrl+C). Here’s a simple example:

#!/bin/bash

cleanup_and_exit() {
    echo -e "\nSignal received! Cleaning up and exiting..."
    exit 0
}

trap cleanup_and_exit SIGINT

echo "This script will run until you press Ctrl+C."
echo "Press Ctrl+C to see the trap in action and exit gracefully."

count=1
while true; do
    echo "Script is running... (iteration $count)"
    sleep 1
    ((count++))
done

Explanation:

  • trap cleanup_and_exit SIGINT: This line sets up a trap for the SIGINT signal. When the signal is received, the cleanup_and_exit function is called.
  • cleanup_and_exit function: This function prints a message and exits the script gracefully.
  • The script runs in an infinite loop, printing a message every second until interrupted.

You can save this script to a file (e.g., trap_example.sh), make it executable with chmod +x trap_example.sh, and run it to see how it handles the SIGINT signal.

0 Comments

no data
Be the first to share your comment!