This site is for tech Q&A. Please keep your posts focused on the subject at hand.

Ask one question at a time. Don't conflate multiple problems into a single question.

Make sure to include all relevant information in your posts. Try to avoid linking to external sites.

Links to documentation are fine, but in addition you should also quote the relevant parts in your posts.

1 vote

I need to read the lines of a text file into an array in Bash. The simple approach

arr=( $(cat myfile.txt) )

does not work for me, because the lines may contain whitespace, so an input like this

foo bar

would result in an array

[ "foo", "bar", "baz" ]

instead of the desired

[ "foo bar", "baz" ]

I can get the desired result by using a loop like this:

declare -a arr=()
while read -r line; do
  arr+=( "$line" )
done < myfile.txt

but that seems a bit overkill.

in Scripting
by (125)
3 20 38
edit history
Are you asking yourself questions?
I'm generating content by answering questions to problems I've encountered to get this thing off the ground, and maybe attract some users.

Please log in or register to answer this question.

1 Answer

0 votes

Since version 4 Bash has a builtin command mapfile (which also has a synonym readarray) that does what you're asking:

mapfile -t arr < myfile.txt
readarray -t arr < myfile.txt

The option -t is to strip trailing newlines from the input.

mapfile and readarray do the same thing, but personally I'd probably prefer the latter since it's clearer what the command does when you read the script.

by (125)
3 20 38
edit history