1

I have some code like the following inside a Bash script:

FileNames=""
while read -r FileName; do
    ...
    FileNames+=" -o -iname \"$FileName\""
    ...
done <"$ListOfFileNames"
FileNames="${FileNames# -o }"
find foo -type f \( $FileNames \)

This was generally working for me until I found that some file names contain spaces (and maybe other special characters). When I added the extra quoting around the use of $FileName to cover these cases, the expansion of $FileNames within the find command starts misbehaving. I have tried various other ways of quoting and escaping and came up empty. I have successfully used variables in many other ways in many other scripts I have written, but this one has baffled me. I am running the script under Cygwin. Is there some nice way to handle this?

knokej
  • 71
  • 7
  • I was just looking for the answer to this myself. [Here ya go.](http://stackoverflow.com/a/143172/6142694) – Daniel M. Capella Apr 01 '16 at 01:23
  • Barmar, the reference you provide did not show up the way I searched, but I see it is basically the same issue. However, I would say that it is not an 'exact duplicate' as it did not have to deal with quoting a nested expansion and then deleting part of the variable (which I got wrong the first time I tried the array method). – knokej Apr 02 '16 at 13:46
  • Daniel, I didn't actually see that the place your link sent me explained my problem with variable expansion within a command, but it's water under the bridge now. – knokej Apr 02 '16 at 13:47

1 Answers1

0

Use an array. Arrays can handle whitespace much better. To be extra safe, also use IFS= to preserve leading whitespace with read.

FileNames=(-false)
while IFS= read -r FileName; do
    ...
    FileNames+=(-o -iname "$FileName")
    ...
done < "$ListOfFileNames"
find foo -type f \( "${FileNames[@]}" \)
John Kugelman
  • 349,597
  • 67
  • 533
  • 578
  • Thanks John, this worked except I had to figure out how to correctly get the `FileNames="${FileNames# -o }"` functionality. At first I just set the first array element to "", but that didn't work. `unset` did work. – knokej Apr 02 '16 at 13:50