How to prevent signals (e.g., SIGINT via Ctrl-c) from affecting child process of bash script

Solution Verified - Updated -

Issue

  • Example issue #1: interactive shell script spawns long-running process
    How to make the whole script, including this process, ignore Ctrl-c
    Example code:

    #!/bin/bash
    trap '' SIGINT
    ping -c10 localhost
    echo FINISHED
    
  • Example issue #2: interactive shell script spawns a long-running process in the background
    How to make the whole script, including this process, ignore Ctrl-c
    Example code:

    #!/bin/bash
    trap '' SIGINT
    ping -c10 localhost &
    wait
    echo FINISHED
    
  • Note that in both examples, the terminal will pass the Ctrl-c-triggered SIGINT on to the script's process group -- i.e., while the script itself will ignore SIGINT, the ping command will still receive it and exit early

Subscriber exclusive content

A Red Hat subscription provides unlimited access to our knowledgebase of over 48,000 articles and solutions.

Current Customers and Partners

Log in for full access

Log In
Close

Welcome! Check out the Getting Started with Red Hat page for quick tours and guides for common tasks.