title: Trying to close all child processes when I interrupt my bash script
body: <p>I have written a bash script to carry out some tests on my system. The tests run in the background and in parallel. The tests can take a long time and sometimes I may wish to abort the tests part way through.</p>
  
  <p>If I Control+C then it aborts the parent script, but leaves the various children running. I wish to make it so that I can hit Control+C or otherwise to quit and then kill all child processes running in the background. I have a bit of code that does the job if I'm running running the background jobs directly from the terminal, but it doesn't work in my script.</p>
  
  <p>I have a minimal working example.</p>
  
  <p>I have tried using trap in combination with pgrep -P $$.</p>
  
  <pre><code>#!/bin/bash
  
  trap 'kill -n 2 $(pgrep -P $$)' 2
  sleep 10 &amp;
  wait
  </code></pre>
  
  <p>I was hoping that on hitting control+c (SIGINT) would kill everything that the script started but it actually says:</p>
  
  <pre><code>./breakTest.sh: line 1: kill: (3220) - No such process
  </code></pre>
  
  <p>This number changes, but doesn't seem to apply to any running processes, so I don't know where it is coming from.</p>
  
  <p>I guess if the contents of the trap command get evaluated where the trap command occurs then it might explain the outcome. The 3220 pid might be for pgrep itself.</p>
  
  <p>I'd appreciate some insight here</p>
  
  <p>Thanks</p>