How to populate a bash array with a file's lines
<p>Populating an array from a file should be basic, but I can't get it to work.</p>

<pre><code>    #!/bin/bash
    declare -a a
    i=0
    cat "file.txt" | while read line; do
        a[$i]="$line"
        i=$(($i + 1))
    done
    echo "${a[0]}"
</code></pre>

<p>This prints an empty line. For a file that contains the lines "Foo" and "Bar", here's the output from bash -x:</p>

<pre><code>    + declare -a a
    + i=0
    + cat file.txt
    + read line
    + a[$i]=Foo
    + i=1
    + read line
    + a[$i]=Bar
    + i=2
    + read line
    + echo ''
</code></pre>

<p>I can't even get the readarray builtin working:</p>

<pre><code>    #!/bin/bash
    declare -a b
    cat "file.txt" | readarray b
    echo "${b[0]}"

    + declare -a b
    + cat file.txt
    + readarray b
    + echo ''
</code></pre>

<p>What am I doing wrong here?</p>