title: Preventing a child process (HandbrakeCLI) from causing the parent script to exit
body: <p>I have a batch conversion script to turn .mkvs of various dimensions into ipod/iphone sized .mp4s, cropping/scaling to suit. Determining the original dimensions, required crop, output file is all working fine. However, on successful completion of the first conversion, HandbrakeCLI causes the parent script to exit. Why would this be? And how can I stop it?</p>
  
  <p>The code, as it currently stands:</p>
  
  <pre><code>#!/bin/bash
  find . -name "*.mkv" | while read FILE
  do
      # What would the output file be?
      DST=../Touch/$(dirname "$FILE")
      MKV=$(basename "$FILE")
      MP4=${MKV%%.mkv}.mp4
  
      # If it already exists, don't overwrite it
      if [ -e "$DST/$MP4" ]
      then
          echo "NOT overwriting $DST/$MP4"
      else
  
          # Stuff to determine dimensions/cropping removed for brevity
  
          HandbrakeCLI --preset "iPhone &amp; iPod Touch" --vb 900 --crop $crop -i "$FILE" -o "$DST/$MP4" &gt; /dev/null 2&gt;&amp;1
  
          if [ $? != 0 ]
          then
              echo "$FILE had problems" &gt;&gt; errors.log  
          fi
       fi
  done
  </code></pre>
  
  <p>I have additionally tried it with a trap, but that didn't change the behaviour (although the last trap did fire)</p>
  
  <pre><code>trap "echo Handbrake SIGINT-d"  SIGINT
  trap "echo Handbrake SIGTERM-d" SIGTERM
  trap "echo Handbrake EXIT-d"    EXIT
  trap "echo Handbrake 0-d"       0
  </code></pre>
  
  <p>Edited to add:</p>
  
  <p>The fact that the '0' trap fired prompted me to investigate why that might be. Executing as <code>bash -x $script</code> revealed that the <code>find | while read</code> loop is ending prematurely.</p>
  
  <p>I've re-factored the find and encode into separate scripts. The find loop is now:</p>
  
  <pre><code>find . -name "*.mkv" | while read FILE
  do
      handbrake-touch "$FILE"
  
      if [ $? != 0 ]
      then
          echo "$FILE had problems" &gt;&gt; errors.log  
      fi
  done
  </code></pre>
  
  <p>The behaviour remains the same - one encode followed by the while loop ending. If I just put an 'echo $FILE' in place of the 'handbrake-touch', all the files are listed. The current directory doesn't change (I was wondering what might break the <code>find | while</code>).</p>