title: Exit when one process in pipe fails
body: <p>The goal was to make a simple unintrusive wrapper that traces stdin and stdout to stderr:</p>
  
  <pre><code>#!/bin/bash
  
  tee /dev/stderr | ./script.sh | tee /dev/stderr
  
  exit ${PIPESTATUS[1]}
  </code></pre>
  
  <p>Test script <code>script.sh</code>:</p>
  
  <pre><code>#!/bin/bash
  
  echo asd
  sleep 1
  exit 4
  </code></pre>
  
  <p>But when the script exits, it doesn't terminate the wrapper. Possible solution is to end the first <code>tee</code> from the second command of the pipe:</p>
  
  <pre><code>#!/bin/bash
  
  # Second subshell will get the PID of the first one through the pipe.
  # It will be able to kill the whole script by killing the first subshell.
  
  # Create a temporary named pipe (it's safe, conflicts will throw an error).
  pipe=$(mktemp -u)
  if ! mkfifo $pipe; then
      echo "ERROR: debug tracing pipe creation failed." &gt;&amp;2
      exit 1
  fi
  
  # Attach it to file descriptor 3.
  exec 3&lt;&gt;$pipe
  
  # Unlink the named pipe.
  rm $pipe
  
  (echo $BASHPID &gt;&amp;3; tee /dev/stderr) | (./script.sh; r=$?; kill $(head -n1 &lt;&amp;3); exit $r) | tee /dev/stderr
  
  exit ${PIPESTATUS[1]}
  </code></pre>
  
  <p>That's a lot of code. Is there another way?</p>