How can I safely read each line of a file into an array in Bash 3.2?
Asked by
MellowPine47
I need to read a text file line by line and store the results in an array. My current function works in newer Bash versions by using a variable name passed as an argument, but it relies on array features that are unavailable on macOS's default Bash 3.2. I also ran into problems with backslashes and other escaped characters being altered, apparently because of eval. What is the safest way to preserve each line exactly while remaining compatible with Bash 3.2?
Answers
The simplest solution may be to install a current Bash through a package manager such as Homebrew or MacPorts. The system Bash on older macOS releases is 3.2, so newer array conveniences are unavailable. Once a recent Bash is used, the original function works as expected.
Reply to this answer
A loop using cat piped into read may appear to work, but it is not ideal because the loop can run in a subshell and any array changes may be lost afterward. The important pieces are IFS= and read -r, which preserve whitespace and backslashes: while IFS= read -r line; do ...; done < "$file_path".
Reply to this answer
Add your answer
Answers are reviewed before publication.
MellowPine47: That is what I ended up doing. After installing a newer Bash, the function started behaving correctly without changing the file contents.