title: Read from two files in simultaneously in bash when they may be missing trailing newlines
body: <p>I have two text files that I'm trying to read through line by line at the same time. The files do not necessarily have the same number of lines, and the script should stop reading when it reaches the end of either file. I'd like to keep this as "pure" bash as possible. Most of the solutions I've found for doing this suggest something of the form:</p>
  
  <pre><code>while read -r f1 &amp;&amp; read -r f2 &lt;&amp;3; do
      echo "$f1"
      echo "$f2"
  done &lt; file1 3&lt;file2
  </code></pre>
  
  <p>However this fails if the last line of a file does not have a newline.</p>
  
  <p>If I were only reading one file I would do something like:</p>
  
  <pre><code>while IFS='' read -r line || [[ -n "$line" ]]; do
      echo "$line"
  done &lt; file1
  </code></pre>
  
  <p>but when I try to extend this to reading multiple files by doing things like:</p>
  
  <pre><code>while IFS='' read -r f1 || [[ -n "$f1" ]] &amp;&amp; read -r f2 &lt;&amp;3 || [[ -n "$f2" ]]; do
      echo "$f1"
      echo "$f2"
  done &lt; file1 3&lt;file2
  </code></pre>
  
  <p>or</p>
  
  <pre><code>while IFS='' read -r f1 &amp;&amp; read -r f2 &lt;&amp;3 || [[ -n "$f1" || -n "$f2" ]]; do
      echo "$f1"
      echo "$f2"
  done &lt; file1 3&lt;file2
  </code></pre>
  
  <p>I can't seem to get the logic right and the loop either doesn't terminate or finishes without reading the last line.</p>
  
  <p>I can get the desired behavior using:</p>
  
  <pre><code>while true; do
      read -r f1 &lt;&amp;3 || if [[ -z "$f1" ]]; then break; fi;
      read -r f2 &lt;&amp;4 || if [[ -z "$f2" ]]; then break; fi;
      echo "$f1"
      echo "$f2"
  done 3&lt;file1 4&lt;file2
  </code></pre>
  
  <p>However this doesn't seem to match the normal (?)</p>
  
  <pre><code>while ... read ...; do
       ... 
  done
  </code></pre>
  
  <p>idiom that I see for reading files.</p>
  
  <p>Is there a better way to simultaneously read from two files that might have differing numbers of lines and last lines that are not newline terminated?</p>
  
  <p>What are the potential drawbacks of my way of reading the files?</p>