π¨ Bash: Trap, Signals & Exit Codes β Handle trap, exit, and Script Termination
π§² Introduction to Bash trap, Signals, and Exit Codes β Graceful Error and Signal Handling
When writing production-grade Bash scripts, itβs crucial to handle unexpected interruptions, clean up temporary resources, and signal success or failure. Bash provides powerful mechanisms for this using:
- trapβ to catch signals or script exits
- exitβ to return a specific exit code
- Exit status codes ($?) β to determine success or failure
These tools allow your scripts to react safely to errors, Ctrl+C interruptions, and resource leaks.
π― In this article, youβll learn:
- How to use trapto catch signals likeSIGINT
- How exitworks and how to set custom exit codes
- What $?represents and how to use it
- Best practices for cleaning up and scripting defensively
π What Is exit in Bash?
The exit command terminates the script and returns a numeric exit status to the shell.
β Example:
exit 0    # Successful exit
exit 1    # Failure or error
π‘ By convention,
0= success, any non-zero = error.
You can also use exit inside functions to end script execution early.
π What Is $? in Bash?
$? holds the exit status of the last command.
π§ͺ Example:
ls file.txt
echo "Exit status: $?"
β Output (if file not found):
ls: cannot access 'file.txt': No such file or directory
Exit status: 2
π§ Always check
$?after a critical command to verify success.
π§² Using trap to Catch Signals
The trap command lets you run cleanup code when a signal is received (e.g., SIGINT for Ctrl+C, EXIT on script termination).
π Syntax:
trap 'commands' SIGNAL
π§ͺ Example 1: Handle Ctrl+C with SIGINT
trap 'echo "Script interrupted"; exit 1' SIGINT
while true; do
  echo "Running... (Press Ctrl+C to stop)"
  sleep 2
done
β
 Output on Ctrl+C:
Script interrupted
π§ͺ Example 2: Clean Up Temporary Files on Exit
trap 'rm -f /tmp/tempfile; echo "Cleaned up"; exit' EXIT
touch /tmp/tempfile
echo "Doing some work..."
sleep 3
β Output:
Doing some work...
Cleaned up
β
EXITis a pseudo-signal triggered when the script exits for any reason.
π’ Common Bash Signals You Can Trap
| Signal | Description | Example Use | 
|---|---|---|
| INT | Interrupt ( Ctrl+C) | Graceful cancel | 
| TERM | Termination signal | Clean up before stopping | 
| EXIT | Script is exiting | Final cleanup or logging | 
| ERR | A command fails | Global error handler (with set -e) | 
π§ Best Practices for Exit Handling
| Practice | Why It Matters | 
|---|---|
| Always set exit codes | Communicates status to calling processes | 
| Use trapfor cleanup | Avoids leaving temp files or locks | 
| Check $?after risky commands | Enables conditional logic after execution | 
| Use named functions in trap | Keeps traps organized and readable | 
π Summary β Bash Trap, Signals & Exit Codes
Understanding trap, signals, and exit codes gives your scripts reliability, cleanup logic, and professional polish. It ensures you handle user interruptions, signal failures, and leave no trace when exiting.
π Key Takeaways:
- Use exit Nto return status (0 = success)
- Use $?to inspect the last commandβs exit code
- Use trapto catchEXIT,SIGINT,TERM, etc.
- Always clean up resources before exit
βοΈ Real-world Uses:
- Scripts that manage temp files or network sockets
- Long-running tasks that may be interrupted
- CI/CD pipelines where failure codes must be reported
β FAQ β Bash Trap, Signals & Exit Codes
β What is the default exit code for exit in Bash?
β
 If not specified, exit returns the exit code of the last command ($?).
β What is the difference between exit 1 and exit 0?
β
 exit 0 signals success, exit 1 (or any non-zero) signals failure.
β Can I trap multiple signals at once?
β
 Yes:
trap 'cleanup' SIGINT SIGTERM
β What does trap 'cmd' EXIT do?
β
 Runs cmd right before the script exits, no matter how it ends.
β Can I use a function name in a trap?
β
 Yes:
trap cleanup EXIT
cleanup() { echo "Cleaning..."; }
Share Now :
