πŸ”§ 4. Bash Functions & Scripting
Estimated reading: 3 minutes 40 views

🚨 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 trap to catch signals like SIGINT
  • How exit works 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

βœ… EXIT is a pseudo-signal triggered when the script exits for any reason.


πŸ”’ Common Bash Signals You Can Trap

SignalDescriptionExample Use
INTInterrupt (Ctrl+C)Graceful cancel
TERMTermination signalClean up before stopping
EXITScript is exitingFinal cleanup or logging
ERRA command failsGlobal error handler (with set -e)

🧠 Best Practices for Exit Handling

PracticeWhy It Matters
Always set exit codesCommunicates status to calling processes
Use trap for cleanupAvoids leaving temp files or locks
Check $? after risky commandsEnables conditional logic after execution
Use named functions in trapKeeps 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 N to return status (0 = success)
  • Use $? to inspect the last command’s exit code
  • Use trap to catch EXIT, 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 :

Leave a Reply

Your email address will not be published. Required fields are marked *

Share

🟒 Bash: Trap, Signals & Exit Codes (trap, exit)

Or Copy Link

CONTENTS
Scroll to Top