How to trap a signal in a shell script

Solution Verified - Updated -

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, and 2 are all equivalent
    • Example:

      #!/bin/bash
      trap "" INT TERM
      ...
      script code here
      ...
      
  • Pitfalls:

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