Bash Using "trap" to react to signals and system events

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Extensions
> Step 2: And Like the video. BONUS: You can also share it!

Syntax

  • trap action sigspec... # Run "action" on a list of signals
  • trap sigspec... # Omitting action resets traps for signals

Parameters

ParameterMeaning
-pList currently installed traps
-lList signal names and corresponding numbers

Remarks

The trap utility is a special shell built-in. It's defined in POSIX, but bash adds some useful extensions as well.

Examples that are POSIX-compatible start with #!/bin/sh, and examples that start with #!/bin/bash use a bash extension.

The signals can either be a signal number, a signal name (without the SIG prefix), or the special keyword EXIT.

Those guaranteed by POSIX are:

NumberNameNotes
0EXITAlways run on shell exit, regardless of exit code
1SIGHUP
2SIGINTThis is what ^C sends
3SIGQUIT
6SIGABRT
9SIGKILL
14SIGALRM
15SIGTERMThis is what kill sends by default


Got any Bash Question?