[Code Example] Read file line by line and store in array using bash script


In this article we will provide you bash script code to read a file line by line and store it in array. This code can preserve empty lines or discard them according to the need.

Code Example –

1. Bash <4 (discarding empty lines).


IFS=$'\n' read -d "" -ra file_data < "file"

echo $file_data

2. Bash <4 (preserving empty lines)


while read -r line; do
done < "file"

echo $file_data

3. For Bash 4+


mapfile -t file_data < "file"

echo $file_data

Inspired from Dylan Araps

Sign Up for Our Newsletters

Get only the best articles delivered to your mail

You May Also Like