0
0
Bash Scriptingscripting~5 mins

Signal handling with trap in Bash Scripting

Choose your learning style9 modes available
Introduction
Signal handling lets your script respond to events like pressing Ctrl+C. Using trap helps your script clean up or stop safely.
You want to stop a script safely when a user presses Ctrl+C.
You need to delete temporary files if the script is interrupted.
You want to run a command when the script exits for any reason.
You want to ignore certain signals to keep the script running.
You want to log a message when the script receives a specific signal.
Syntax
Bash Scripting
trap 'commands' SIGNALS
Replace 'commands' with the commands to run when the signal is caught.
Replace SIGNALS with one or more signals like SIGINT, SIGTERM, EXIT.
Examples
Runs a message and exits when you press Ctrl+C (SIGINT).
Bash Scripting
trap 'echo "Script interrupted!"; exit' SIGINT
Deletes a temp file when the script ends for any reason.
Bash Scripting
trap 'rm -f /tmp/tempfile' EXIT
Ignores the SIGTERM signal so the script won't stop from it.
Bash Scripting
trap '' SIGTERM
Sample Program
This script runs an endless loop. When you press Ctrl+C, it prints a message and exits safely.
Bash Scripting
#!/bin/bash

trap 'echo "You pressed Ctrl+C! Cleaning up..."; exit' SIGINT

echo "Script is running. Press Ctrl+C to stop."

while true; do
  sleep 1
done
OutputSuccess
Important Notes
Use EXIT signal to run commands when the script finishes normally or is interrupted.
You can trap multiple signals by listing them after the commands, like: trap 'commands' SIGINT SIGTERM.
Always test your trap commands to make sure they do what you want.
Summary
trap lets your script catch signals like Ctrl+C and respond.
Use trap to clean up or stop safely when interrupted.
You can run commands on exit or ignore signals with trap.