How to trap a signal in a shell script
Environment
- Red Hat Enterprise Linux
- bash
Issue
- Do not want the script to be interrupted by
Clt+C
(Signal INT), for example scripts to backup databases, can shell script handle such signal?
Resolution
-
Use the
trap "" INT
command to ignore the interrupt signal (triggered by Ctrl-c)- Additional signals (as reported by
kill -l
) can be specified - Note that
SIGINT
,INT
, and2
are all equivalent -
Example:
#!/bin/bash trap "" INT TERM ... script code here ...
- Additional signals (as reported by
-
Pitfalls:
- If a script is executed interactively from a terminal, the above solution will not always prevent the user from using Ctrl-c
- This depends on the application being called by the script -- for example,
ping
orrsync
will both still shutdown in this situation - To address this, see article:
How to prevent signals (e.g., SIGINT via Ctrl-c) from affecting child process of bash script - See also
help trap
orman trap
This solution is part of Red Hat’s fast-track publication program, providing a huge library of solutions that Red Hat engineers have created while supporting our customers. To give you the knowledge you need the instant it becomes available, these articles may be presented in a raw and unedited form.
Comments