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).
#!/bin/bash IFS=$'\n' read -d "" -ra file_data < "file" echo $file_data
2. Bash <4 (preserving empty lines)
#!/bin/bash while read -r line; do file_data+=("$line") done < "file" echo $file_data
3. For Bash 4+
#!/bin/bash mapfile -t file_data < "file" echo $file_data
Inspired from Dylan Araps