trap

Trap

The trap command is a shell built-in that allows you to catch and handle signals sent to your shell session. A signal is a notification from the operating system to the shell or running programs, typically indicating something has gone wrong or needs attention.

What’s it for?

You might use trap in situations where:

  • You want to clean up resources before exiting a program.
  • You need to handle specific signals, like when the user presses Ctrl+C (SIGINT) or closes the terminal window (SIGHUP).
  • You’re working with processes that produce output and want to redirect it to a file or pipe.

How to use it?

The basic syntax is:

bash
trap command signal_list

Here, command is what you want to execute in response to the signal, and signal_list specifies which signals to trap. You can specify multiple signals by separating them with commas (e.g., SIGHUP,SIGINT,SIGQUIT).

For example:

bash
trap "echo 'Terminating...'; exit" SIGHUP SIGINT SIGQUIT

This sets up the shell session to execute a command that prints „Terminating…“ and then exits upon receiving any of those signals.

Special hacks

  1. Cleaning up resources: If you’re using a lot of temporary files or sockets within a script, consider trapping EXIT (with a zero argument) to ensure these resources are cleaned up properly before your program terminates.
  2. Executing commands at exit: Use trap with the EXIT signal and a non-zero argument to run specific cleanup commands or functions. This can be handy for cleaning up processes that were spawned within your script.
  3. Customizing Ctrl+C behavior: Trap SIGINT to execute custom code when the user presses Ctrl+C, potentially ignoring the default exit behavior.

Experience level

The use of trap is more relevant to intermediate or advanced users who want to:

  • Enhance their shell scripting capabilities.
  • Improve error handling and cleanup within complex scripts.
  • Utilize signals for program flow control or resource management.