What does the `trap` command do in Bash?

QuestionsQuestions8 SkillsProBash Trap CommandOct, 15 2025
0125

The trap command in Bash is used to catch and handle signals, interruptions, and specific events in a script. It allows you to define actions that should be taken when certain signals are received, enabling you to manage unexpected behavior gracefully.

Key Features of trap:

  1. Signal Handling: You can specify commands to execute when the script receives signals like SIGINT (interrupt), SIGTERM (termination), etc.

  2. Cleanup Actions: It is commonly used to perform cleanup tasks, such as deleting temporary files or closing network connections, before the script exits.

  3. User Interrupts: You can handle user interrupts (like pressing Ctrl+C) to ensure that the script exits cleanly.

Basic Syntax:

trap 'commands' SIGNAL

Example:

#!/bin/bash

# Define a cleanup function
cleanup() {
  echo "Cleaning up..."
  rm -f temp_file.txt
}

# Set trap for SIGINT (Ctrl+C)
trap cleanup SIGINT

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

In this example, if the user presses Ctrl+C, the cleanup function will be called, allowing the script to perform cleanup before exiting.

0 Comments

no data
Be the first to share your comment!