3

I'm using this code to load file into array in bash:

IFS=$'\n' read -d '' -r -a LINES < "$PAR1"

But unfortunately this code skips empty lines.

I tried the next code:

IFS=$'\n' read -r -a LINES < "$PAR1"

But this variant only loads one line.

How do I load file to array in bash, without skipping empty lines?

P.S. I check the number of loaded lines by the next command:

echo ${#LINES[@]}
2
  • 1
    All-caps variable names are reserved by convention to avoid overwriting system-impacting names by mistake. See fourth paragraph of pubs.opengroup.org/onlinepubs/009695399/basedefs/…, keeping in mind that environment variables and shell variables share a namespace. Commented Aug 5, 2015 at 23:01
  • See also: Convert multiline string to array. I've just updated my answer here to highlight this important distinction between read and mapfile: read does not keep empty elements in the array, but mapfile does. Commented Mar 28, 2022 at 6:38

2 Answers 2

3

You can use mapfile available in BASH 4+

mapfile -t lines < "$PAR1"
Sign up to request clarification or add additional context in comments.

Comments

2

To avoid doing anything fancy, and stay compatible with all versions of bash in common use (as of this writing, Apple is shipping bash 3.2.x to avoid needing to comply with the GPLv3):

lines=( )
while IFS= read -r line; do
  lines+=( "$line" )
done

See also BashFAQ #001.

4 Comments

Great thanks! As for the last line I used the code from your link: lines=( ) while IFS= read -r line do lines+=( "$line" ) done < "$PAR1" [[ -n $line ]] && lines+=( "$line" )
Correct- the more complete answer (to fix skipping the last line) is to add [[ -n $line ]] && lines+=( "$line" ) at the end. Learned this the hard way!
@skupjoe, or you can make it while IFS= read -r line || [[ $line ]]; do. You only need that if you use files made by someone who runs Windows (or tools that follow Microsoft's lead in considering newlines line separators instead of terminators), though, so if you're a right-thinking person who uses UNIX and only uses files made by people who do likewise, it's completely unnecessary, right? :)
@CharlesDuffy Hmm, well, creating and using such a file that is only one entry long which is in LF format and doesn't end with a newline in VSCode (yes, from Windows machine) seems to exhibit this behavior when I then use this file in a Bash script that loads it to an array, executed from OSX, synced via Dropbox. Complicated, I know, but I dev cross-platform and from many different clients :D

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.