What are other special Bash signals?

QuestionsQuestions8 SkillsProDec, 21 2025
0107

Great question! While we often focus on system signals like SIGINT or SIGTERM, Bash has several special "pseudo-signals" that are internal to the shell itself. These are incredibly powerful for automation and debugging.

Here are the most common special Bash signals:

1. EXIT (or 0)

This is arguably the most useful one. A trap on EXIT will execute when the script terminates for any reason, including:

  • The script reaches the end naturally.
  • The script executes the exit command.
  • The script is killed by a signal (like SIGINT or SIGTERM).

Example:

trap "echo 'Cleaning up...'; rm -f temp_file.txt" EXIT

2. ERR

This triggers whenever a command inside your script returns a non-zero exit status (indicating failure). This is great for error handling without having to check if [ $? -ne 0 ] after every single line.

  • Note: It doesn't trigger if the failed command is part of a loop condition or an if statement.

Example:

trap "echo 'An error occurred on the last command!'" ERR

3. DEBUG

This triggers before every single command is executed in the script. It is mostly used for advanced debugging or logging the progress of a script step-by-step.

Example:

trap 'echo "Executing: $BASH_COMMAND"' DEBUG

4. RETURN

This triggers when a shell function finishes executing or when a script executed with the source (or .) command finishes. It’s useful if you are writing complex libraries of functions and want to track when you're leaving a specific scope.


Summary Table

Signal When it triggers Use Case
EXIT When the shell exits General cleanup (deleting files, closing ports).
ERR When a command fails Error logging or manual "try-catch" logic.
DEBUG Before every command Performance monitoring or deep debugging.
RETURN When a function returns Tracking function flow in complex scripts.

You can explore these by creating a small script and adding trap "echo 'Triggered EXIT'" EXIT to the top to see it in action! Do you have a specific scenario in mind where you might want to use one of these?

0 Comments

no data
Be the first to share your comment!