Bash Trap Ctrl+C (SIGINT) | Handle Signals with Examples

Bash Trap Ctrl+C (SIGINT) | Handle Signals with Examples

Bash Trap Ctrl+C

Capture Ctrl+C (SIGINT) Example

Here is a simple while loop to demonstrate the behavior:

bash
#!/bin/bash

trap 'echo "Ctrl+C detected. Exiting..."; exit' INT

echo "Press Ctrl+C to test"
while true; do
    sleep 1
done

Explanation

  • INT represents 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)

SignalNameDescription
2SIGINTTriggered by Ctrl+C
15SIGTERMGraceful termination signal
0EXITRuns when script exits
1SIGHUPTerminal closed
3SIGQUITCtrl+\ signal

Example using multiple signals:

bash
trap 'echo "Cleanup before exit"; rm -f /tmp/testfile' INT TERM EXIT

Tip

  • Use INT to capture Ctrl+C
  • Use TERM for graceful shutdown
  • Use EXIT for 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.

bash
$ trap -l | grep INT
2) SIGINT

Explanation

  • SIGINT is signal number 2
  • It tells the program to stop execution
  • By default, most programs terminate immediately when SIGINT is received

Example

bash
sleep 100

Pressing Ctrl+C will terminate the command instantly.

Signal Numbers and Names

Linux supports many signals that can be sent to processes.

List all signals:

bash
trap -l

Common signals:

NumberSignalDescription
1SIGHUPTerminal closed
2SIGINTCtrl+C interrupt
3SIGQUITCtrl+\ quit
9SIGKILLForce kill (cannot be trapped)
15SIGTERMGraceful termination

Tip

  • Use signal names (SIGINT) instead of numbers for readability
  • Some signals like SIGKILL cannot be trapped

Bash Trap Command (Syntax & Basics)

Basic Trap Syntax

bash
trap 'commands' SIGNAL

Example

bash
trap 'echo "Interrupted!"; exit' INT

Explanation

  • 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.

bash
trap 'echo "Cleaning up..."; rm -f /tmp/file' INT TERM EXIT

Explanation

  • INT → Ctrl+C
  • TERM → graceful termination
  • EXIT → 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.

bash
#!/bin/bash

trap 'echo "Ctrl+C detected. Exiting safely..."; exit' INT

echo "Running script. Press Ctrl+C to stop."

while true; do
    sleep 1
done

Explanation

  • INT represents 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.

bash
#!/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
done

Explanation

  • 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.

bash
trap 'rm -f /tmp/app.log; echo "Logs cleaned"' EXIT

Handle 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.

bash
trap 'echo "Process interrupted. Saving state..."; exit' INT

Prevent Script Termination (Ignore Ctrl+C)

This example ignores the Ctrl+C signal completely, allowing the script to continue running without interruption.

bash
trap '' INT

Explanation

  • Ignores Ctrl+C completely
  • Script continues running

Advanced Trap Usage

Trap Multiple Signals (INT, TERM, EXIT)

bash
trap 'echo "Cleaning up before exit"; rm -f /tmp/file' INT TERM EXIT

Explanation

  • Handles multiple signals in one place
  • Ensures cleanup happens in all exit scenarios

Reset Trap to Default Behavior

bash
trap - INT

Explanation

  • Removes custom trap
  • Restores default behavior (Ctrl+C will terminate script)

Ignore Signals in Bash Script

bash
trap '' TERM

Explanation

  • 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

bash
trap "echo $var" INT
  • Variables are expanded immediately when trap is set
  • Not when the signal is received

Fix

bash
trap 'echo $var' INT

Explanation

  • 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

  • exit is explicitly called inside the trap
  • Signal is not handled properly
  • Script receives another signal (like SIGTERM)

Fix

bash
trap 'echo "Ctrl+C captured";' INT

Explanation

  • Avoid using exit unless required
  • Ensure trap handles only intended signals

Trap Not Triggered in Subshell

Traps may not work as expected inside subshells or child processes.

Problem

bash
( trap 'echo "Ctrl+C captured"' INT; sleep 10 )
  • Subshell has its own signal handling
  • Parent trap may not apply

Fix

bash
trap 'echo "Ctrl+C captured"' INT

sleep 10

Explanation

  • 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 trap allows 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

Official Documentation

Omer Cakmak

Omer Cakmak

Linux Administrator

Highly skilled at managing Debian, Ubuntu, CentOS, Oracle Linux, and Red Hat servers. Proficient in bash scripting, Ansible, and AWX central server management, he handles server operations on OpenStack, KVM, Proxmox, and VMware.