0

I would like to take the output of something that returns lines of elements possibly containing spaces to a bash array, with each line getting its own array element.

So for example:

find . -name \*.jpg

... may return a list of filenames. I want each filename to be assigned to an array. The simple solution doesn't work in general, because if there are spaces in filenames, the words get their own array element.

For example, start with this list of files in a directory:

FILE1.jpg
FILE2.jpg
FILE WITH SPACES.jpg

Try:

FILES=( $(find . -name \*.jpg) )

And you get (<> added for emphasis of individual elements):

$ for f in "${FILES[@]}"; do echo "<$f>"; done
<./FILE>
<WITH>
<SPACES.jpg>
<./FILE1.jpg>
<./FILE2.jpg>

This is not likely what you want.

How do you assign lines to array elements regardless of the lines containing spaces?

1
  • Ok; go ahead and delete it, then. I thought I could add some value by providing a way to do it without -print0, but it's ok. Thanks anyway. Commented Dec 9, 2015 at 2:47

1 Answer 1

1

Set IFS before making the assignment. This allows bash to ignore the spaces by using only "\n" as the delimiter:

IFS=$'\n'
FILES=( $(find . -name \*.jpg) )

Now you get the result:

for f in "${FILES[@]}"; do echo "<$f>"; done
<./FILE WITH SPACES.jpg>
<./FILE1.jpg>
<./FILE2.jpg>

Note that how you access the array is important as well. This is covered in a similar question: BASH array with spaces in elements

Sign up to request clarification or add additional context in comments.

1 Comment

This isn't completely correct. It does not work for filenames that themselves contain newlines. It also may not work when filenames contain pattern metacharacters such as * and ?.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.