Skip to main content
InterviewHubPRO
Section Overview
Q14

Question 14 of 50

Part 2: Core Architecture & Implementation (Mid-Level)

28%
Bash & Shell Scripting (50 Qs)•Part 2: Core Architecture & Implementation (Mid-Level)

What are Signals and the `trap` command in Bash?

senior LevelMost AskedCode ExampleSignalsSystem Design

In Simple Words: trap catches OS signals sent to the script process and executes a cleanup function before exit:

  • Signals: SIGINT (Ctrl+C), SIGTERM (kill), EXIT (normal or abnormal script exit).
  • Guarantees that temporary files and lockfiles are deleted even if the script is interrupted!
bash
temp_dir=$(mktemp -d)

cleanup() {
    echo "Cleaning up temporary directory: $temp_dir"
    rm -rf "$temp_dir"
}
trap cleanup EXIT # Automatically runs on ANY exit!