Read lines from a file into a Bash array

Homunculus Reticulli picture Homunculus Reticulli · Jul 9, 2012 · Viewed 443k times · Source

I am trying to read a file containing lines into a Bash array.

I have tried the following so far:

Attempt1

a=( $( cat /path/to/filename ) )

Attempt2

index=0
while read line ; do
    MYARRAY[$index]="$line"
    index=$(($index+1))
done < /path/to/filename

Both attempts only return a one element array containing the first line of the file. What am I doing wrong?

I am running bash 4.1.5

Answer

chepner picture chepner · Jul 9, 2012

The readarray command (also spelled mapfile) was introduced in bash 4.0.

readarray -t a < /path/to/filename