[arrays] Read lines from a file into a Bash array

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

This question is related to arrays bash

The answer is


One alternate way if file contains strings without spaces with 1string each line:

fileItemString=$(cat  filename |tr "\n" " ")

fileItemArray=($fileItemString)

Check:

Print whole Array:

${fileItemArray[*]}

Length=${#fileItemArray[@]}

#!/bin/bash
IFS=$'\n' read  -d'' -r -a inlines  < testinput
IFS=$'\n' read  -d'' -r -a  outlines < testoutput
counter=0
cat testinput | while read line; 
do
    echo "$((${inlines[$counter]}-${outlines[$counter]}))"
    counter=$(($counter+1))
done
# OR Do like this
counter=0
readarray a < testinput
readarray b < testoutput
cat testinput | while read myline; 
do
    echo value is: $((${a[$counter]}-${b[$counter]}))
    counter=$(($counter+1))
done

The simplest way to read each line of a file into a bash array is this:

IFS=$'\n' read -d '' -r -a lines < /etc/passwd

Now just index in to the array lines to retrieve each line, e.g.

printf "line 1: %s\n" "${lines[0]}"
printf "line 5: %s\n" "${lines[4]}"

# all lines
echo "${lines[@]}"

Your first attempt was close. Here is the simplistic approach using your idea.

file="somefileondisk"
lines=`cat $file`
for line in $lines; do
        echo "$line"
done

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

readarray -t a < /path/to/filename