How to portable read a text file line by line in bash
<p>For processing a text file in bash line by line, I usually implement a while loop like this:</p>

<pre><code>function doSomething() {
    local inputFile="$1"
    local fd=""
    local line=""
    exec {fd}&lt;"$inputFile" # open file
    echo "Opened ${inputFile} for read using descriptor ${fd}"
    while IFS='' read -r -u $fd line || [[ -n "$line" ]]; do
        echo "read = \"$line\""
    done
    exec {fd}&lt;&amp;- # close file
    return 0
}
</code></pre>

<p>This works on my Linux but unfortunately not in OSX. For OSX I currently have to change the code to something like this:</p>

<pre><code>exec 3&lt;"$inputFile" # open file
while IFS='' read -r -u 3 line || [[ -n "$line" ]]; do
    echo "read = \"$line\""
done
exec 3&lt;&amp;- # close file
</code></pre>

<p>But this has the disadvantage, that I have to manage the file descriptor numbers by myself (in the first script, I let bash choose an available file descriptor number).</p>

<p>Did someone have a solution for this which works for both Linux and OSX?</p>

<p>Note that for some reason, I don't want to use piping or I/O redirection to the complete loop like this (because I don't want to execute the loop in a different process):</p>

<pre><code>while IFS='' read -r line || [[ -n "$line" ]]; do
    echo "read = \"$line\""
done &lt; "$inputFile"
</code></pre>