0
0
Bash-scriptingDebug / FixBeginner · 3 min read

How to Handle Signals in Bash Scripts Correctly

In bash, you handle signals using the trap command, which lets you specify commands to run when the script receives signals like SIGINT (Ctrl+C). This helps you clean up or safely exit instead of abruptly stopping the script.
🔍

Why This Happens

When you run a bash script and press Ctrl+C or the script receives a termination signal, it stops immediately by default. This can leave temporary files or processes running, causing problems.

If you don't handle signals, your script can't clean up or save its state before exiting.

bash
#!/bin/bash

while true; do
  echo "Running... Press Ctrl+C to stop"
  sleep 2
done
Output
Running... Press Ctrl+C to stop Running... Press Ctrl+C to stop ^C
🔧

The Fix

Use the trap command to catch signals like SIGINT and run a cleanup function before the script exits. This lets you handle interrupts gracefully.

bash
#!/bin/bash

cleanup() {
  echo "\nCaught SIGINT, cleaning up..."
  # Add cleanup commands here
  exit 0
}

trap cleanup SIGINT

while true; do
  echo "Running... Press Ctrl+C to stop"
  sleep 2
done
Output
Running... Press Ctrl+C to stop Running... Press Ctrl+C to stop Caught SIGINT, cleaning up...
🛡️

Prevention

Always use trap in scripts that run long tasks or create temporary files. This prevents leaving your system in a bad state if interrupted.

Test your signal handlers by sending signals manually with kill -SIGINT <pid> or pressing Ctrl+C.

Keep cleanup code simple and fast to avoid delays during exit.

⚠️

Related Errors

Common mistakes include:

  • Not using trap, causing abrupt script termination.
  • Using exit inside a trap without cleanup, skipping important steps.
  • Ignoring other signals like SIGHUP or SIGTERM that may also stop your script.

Key Takeaways

Use the trap command to catch signals like SIGINT and run cleanup code.
Always test your signal handlers to ensure graceful script termination.
Include cleanup steps to avoid leaving temporary files or processes.
Handle multiple signals if your script may be stopped in different ways.
Keep signal handler code simple and fast to avoid delays.