0

Writing a small script in bash (MacOS in fact) and I want to use find, with multiple sources. Not normally a problem, but the list of source directories to search is held as a string in a variable. Again, not normally a problem, but some of them contain spaces in their name.

I can construct the full command string and if entered directly at the command prompt (copy and paste in fact) it works as required and expected. But when I try and run it within the script, it flunks out on the spaces in the name and I have been unable to get around this.

I cannot quote the entire source string as that is then just seen as one single item which of course does not exist. I escape each space with a backslash within the string held in the variable and it is simply lost. If I use double backslash, they both remain in place and again it fails. Any method of quoting I have tried is basically ignored, the quotes are seen as normal characters and splitting is done at each space.

I have so far only been able to use eval on the whole command string to get it to work but I felt there ought to be a better solution than this.

Ironically, if I use AppleScript I CAN create a suitable command string and run it perfectly with doShellScript (ok, that's using JXA, but it's the same with actual AppleScript). However, I have so far been unable to find the correct escape mechanism just in a bash script, without resorting to eval.

Anyone suggest a solution to this?

UKenGB
  • 21
  • 2

1 Answers1

0

If possible, don't store all paths in one string. An array is safer and more convenient:

paths=("first path" "second path" "and so on")
find "${paths[@]}"

The find command will expand to

find "first path" "second path" "and so on"

If you have to use the string and don't want to use eval, split the string into an array:

string="first\ path second\ path and\ so\ on"
read -a paths <<< "$string"
find "${paths[@]}"

Paths inside string should use \ to escape spaces; wraping paths inside"" or '' will not work. eval might be the better option here.

Community
  • 1
  • 1
Socowi
  • 25,550
  • 3
  • 32
  • 54
  • But as I said, the paths (well, just directory names) are in a string and not an array. – UKenGB Feb 06 '17 at 14:28
  • @UKenGB Sorry, your question wasn't very clear to me. Could you describe exactly how they are stored in the string. Make an example. Is the format `"first path" "second path"` or `first\ path second\ path` or `first path second path`? – Socowi Feb 06 '17 at 15:13
  • For Apple/JavaScript they are stored as 'iTmeDIRS = 'Audiobooks Home\\ Videos Movies Music Podcasts TV\\ Shows' and iTmeDIRS can be fed to the find command to be used as the source directories in which to search. This works. But I cannot find a way in a bash script to store that list of directories in a variable that can be used in the same way for the find command. However I try to quote/escape the spaces in the names, it simply fails. – UKenGB Feb 07 '17 at 16:27