Creating an array from a text file in Bash Creating an array from a text file in Bash arrays arrays

Creating an array from a text file in Bash


Use the mapfile command:

mapfile -t myArray < file.txt

The error is using for -- the idiomatic way to loop over lines of a file is:

while IFS= read -r line; do echo ">>$line<<"; done < file.txt

See BashFAQ/005 for more details.


mapfile and readarray (which are synonymous) are available in Bash version 4 and above. If you have an older version of Bash, you can use a loop to read the file into an array:

arr=()while IFS= read -r line; do  arr+=("$line")done < file

In case the file has an incomplete (missing newline) last line, you could use this alternative:

arr=()while IFS= read -r line || [[ "$line" ]]; do  arr+=("$line")done < file

Related:


You can do this too:

oldIFS="$IFS"IFS=$'\n' arr=($(<file))IFS="$oldIFS"echo "${arr[1]}" # It will print `A Dog`.

Note:

Filename expansion still occurs. For example, if there's a line with a literal * it will expand to all the files in current folder. So use it only if your file is free of this kind of scenario.