Bash Trap Ctrl+C
Capture Ctrl+C (SIGINT) Example
Here is a simple while loop to demonstrate the behavior:
#!/bin/bash
trap 'echo "Ctrl+C detected. Exiting..."; exit' INT
echo "Press Ctrl+C to test"
while true; do
sleep 1
doneExplanation
INTrepresents the Ctrl+C signal (SIGINT)- When Ctrl+C is pressed, the trap command executes the defined action
- Instead of exiting immediately, the script runs custom logic
Common Signals (INT, TERM, EXIT)
| Signal | Name | Description |
|---|---|---|
2 | SIGINT | Triggered by Ctrl+C |
15 | SIGTERM | Graceful termination signal |
0 | EXIT | Runs when script exits |
1 | SIGHUP | Terminal closed |
3 | SIGQUIT | Ctrl+\ signal |
Example using multiple signals:
trap 'echo "Cleanup before exit"; rm -f /tmp/testfile' INT TERM EXITTip
- Use
INTto capture Ctrl+C - Use
TERMfor graceful shutdown - Use
EXITfor cleanup tasks
What is Ctrl+C Signal in Linux
What Signal Ctrl+C Sends (SIGINT)
Ctrl+C sends the SIGINT (Signal Interrupt) to the process.
$ trap -l | grep INT
2) SIGINTExplanation
- SIGINT is signal number 2
- It tells the program to stop execution
- By default, most programs terminate immediately when SIGINT is received
Example
sleep 100Pressing Ctrl+C will terminate the command instantly.
Signal Numbers and Names
Linux supports many signals that can be sent to processes.
List all signals:
trap -lCommon signals:
| Number | Signal | Description |
|---|---|---|
| 1 | SIGHUP | Terminal closed |
| 2 | SIGINT | Ctrl+C interrupt |
| 3 | SIGQUIT | Ctrl+\ quit |
| 9 | SIGKILL | Force kill (cannot be trapped) |
| 15 | SIGTERM | Graceful termination |
Tip
- Use signal names (
SIGINT) instead of numbers for readability - Some signals like
SIGKILLcannot be trapped
Bash Trap Command (Syntax & Basics)
Basic Trap Syntax
trap 'commands' SIGNALExample
trap 'echo "Interrupted!"; exit' INTExplanation
- Executes the command when SIGINT (Ctrl+C) is received
- Prevents abrupt script termination
- Useful for cleanup and logging
Trap Multiple Signals Example
You can handle multiple signals in a single trap command.
trap 'echo "Cleaning up..."; rm -f /tmp/file' INT TERM EXITExplanation
INT→ Ctrl+CTERM→ graceful terminationEXIT→ runs when script exits
Use case
- Remove temporary files
- Close connections
- Perform cleanup before exit
Capture Ctrl+C in Bash Script
Simple Ctrl+C Trap Example
This example captures Ctrl+C (SIGINT) and executes a custom message before exiting.
#!/bin/bash
trap 'echo "Ctrl+C detected. Exiting safely..."; exit' INT
echo "Running script. Press Ctrl+C to stop."
while true; do
sleep 1
doneExplanation
INTrepresents Ctrl+C- Instead of immediate termination, the trap executes custom logic
- Useful for graceful exits
Trap Ctrl+C with Cleanup Function
A better approach is to define a function and call it when the signal is received.
#!/bin/bash
cleanup() {
echo "Cleaning up resources..."
rm -f /tmp/testfile
exit
}
trap cleanup INT
touch /tmp/testfile
while true; do
echo "Script running..."
sleep 2
doneExplanation
- Cleanup logic is separated into a function
- Improves readability and reusability
- Ensures temporary files are removed before exit
Bash Trap Real-World Use Cases
Cleanup Temporary Files on Exit
This example ensures that temporary or log files are automatically removed when the script exits, whether normally or due to interruption.
trap 'rm -f /tmp/app.log; echo "Logs cleaned"' EXITHandle Interrupted Script Safely
This example captures Ctrl+C (SIGINT) and performs a safe exit by executing custom logic such as saving progress or displaying a message.
trap 'echo "Process interrupted. Saving state..."; exit' INTPrevent Script Termination (Ignore Ctrl+C)
This example ignores the Ctrl+C signal completely, allowing the script to continue running without interruption.
trap '' INTExplanation
- Ignores Ctrl+C completely
- Script continues running
Advanced Trap Usage
Trap Multiple Signals (INT, TERM, EXIT)
trap 'echo "Cleaning up before exit"; rm -f /tmp/file' INT TERM EXITExplanation
- Handles multiple signals in one place
- Ensures cleanup happens in all exit scenarios
Reset Trap to Default Behavior
trap - INTExplanation
- Removes custom trap
- Restores default behavior (Ctrl+C will terminate script)
Ignore Signals in Bash Script
trap '' TERMExplanation
- Ignores SIGTERM signal
- Useful for protecting critical processes
Tip
- Do not ignore signals blindly in production
- Always ensure safe exit mechanisms are available
Common Mistakes and Fixes
Trap Not Working (Wrong Quotes)
Using incorrect quotes can cause the trap command to behave unexpectedly.
Problem
trap "echo $var" INT- Variables are expanded immediately when trap is set
- Not when the signal is received
Fix
trap 'echo $var' INTExplanation
- Single quotes delay variable expansion
- Ensures the command runs correctly when the signal occurs
Script Still Exits on Ctrl+C
Sometimes the script exits even after defining a trap.
Possible causes
exitis explicitly called inside the trap- Signal is not handled properly
- Script receives another signal (like SIGTERM)
Fix
trap 'echo "Ctrl+C captured";' INTExplanation
- Avoid using
exitunless required - Ensure trap handles only intended signals
Trap Not Triggered in Subshell
Traps may not work as expected inside subshells or child processes.
Problem
( trap 'echo "Ctrl+C captured"' INT; sleep 10 )- Subshell has its own signal handling
- Parent trap may not apply
Fix
trap 'echo "Ctrl+C captured"' INT
sleep 10Explanation
- Define traps in the main shell context
- Avoid relying on subshells for signal handling
Frequently Asked Questions
1. What signal does Ctrl+C send in Linux?
Ctrl+C sends the SIGINT (signal 2) to a running process, which typically terminates the program unless handled using trap.2. How do I capture Ctrl+C in a Bash script?
You can capture Ctrl+C using the trap command in Bash, for example trap "command" INT to execute custom logic when SIGINT is received.3. What does the trap command do in Bash?
The trap command allows you to define actions that execute when a script receives specific signals such as SIGINT, SIGTERM, or EXIT.4. How do I ignore Ctrl+C in Bash?
You can ignore Ctrl+C using trap "" INT, which prevents the script from terminating when the interrupt signal is received.5. Can Bash trap all signals?
Bash can trap most signals except SIGKILL and SIGSTOP, which cannot be intercepted or handled.Summary
- Ctrl+C sends SIGINT (signal 2) to running processes
- Bash
trapallows handling signals gracefully - Use traps to perform cleanup, logging, or safe exit
- Prefer functions for complex trap logic
- Avoid deep nesting and improper signal handling
- Always test traps with real interruptions


