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?

fbicknel
  • 1,219
  • 13
  • 21
  • 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. – fbicknel Dec 09 '15 at 02:47

1 Answers1

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

Community
  • 1
  • 1
fbicknel
  • 1,219
  • 13
  • 21
  • 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 `?`. – chepner Dec 09 '15 at 02:18