title: bash shutdown hook; or, kill all background processes when main process is killed
body: <p>I have a bash that runs endless commands as background processes:</p>
  
  <pre><code>#!/bin/bash
  
  function xyz() {
    # some awk command
  }
  
  endlesscommand "param 1" | xyz &amp;  # async
  pids=$!
  endlesscommand "param 2" | xyz &amp;  # async
  pids="$pids "$!
  endlesscommand "param 3" | xyz    # sync so the script doesn't leave
  </code></pre>
  
  <p>The only way to stop this script is (must be) Ctrl-C or kill and when that happens, I need to kill all the background processes listed in the $pids variable.</p>
  
  <p>How do I do that?</p>
  
  <p>If it was possible to catch the kill signal on the main process and execute a function when that happens (shutdown hook), I would do something like:</p>
  
  <pre><code>for $pid in $pids; do kill $pid; done;
  </code></pre>
  
  <p>But I can't find how to do this...</p>