Guidelines

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
52 views
52 views

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
baz

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 (275) 7
 
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.

Your answer

Preview

Privacy: Your email address will only be used for sending these notifications.
Anti-spam verification:
By submitting this post you agree to our Terms & Conditions.
To avoid this verification in future, please log in or register.

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 (275) 7
...