title: Exit a bash script when one of the subprocesses exits
body: <p>I'm running several background processes in my script</p>
  
  <pre><code>run_gui()
  {
      exec ... # the real commands here
  }
  </code></pre>
  
  <p>The functions <code>run_ai1(), run_ai2</code> are analogous.</p>
  
  <p>Then I run the functions and do the needed piping</p>
  
  <pre><code>run_gui &amp;
  run_ai1 &amp;
  run_ai2 &amp;
  while true; do
      while true; do
          read -u $ai1_outfd line || echo "Nothing read"
          if [[ $line ]]; then
              : # processing
          fi
      done
      sleep $turndelay
      while true; do
          read -u $ai2_outfd line || echo "nothing read"
          if [[ $line ]]; then
              : # processing
          fi
      done
      sleep $turndelay
  done
  </code></pre>
  
  <p>If any of those three processes exits, I want to check their exit codes and terminate the rest of the processes. For example, if <code>run_ai2</code> exits with exit code 3, then I want to stop the processes <code>run_ai1</code> and <code>run_gui</code> and exit the main script with exit code 1. The correct exitcodes for the different backgrounds processes may differ.</p>
  
  <p>The problem is: how can I detect it? There's the command <code>wait</code> but I don't know in advance which script will finish first. I could run <code>wait</code> as a background process - but it's becoming even more clumsy.</p>
  
  <p>Can you help me please?</p>