How to watch file changes on Mac OSX using FSWatch?

kramer65 picture kramer65 · Jul 4, 2014 · Viewed 12.9k times · Source

I'm trying to use fswatch to translate the following lines from a linux bash script to be able to run it on Mac OSX:

inotifywait -r -m 'myfolder/' | while read MODFILE
do
    echo "something"
done

Since inotifywait doesn't work on Mac OSX I want to substitute the first line for FSWatch. Although the README refers to the fswatch man page, it doesn't provide a link to it and a search around the internet doesn't get me anything. So I tried messing around a bit.

I created a folder called testfswatch/ and I tried running the following commands in the parent folder and then adding and changing files on the testfswatch/ folder:

fswatch -o testfswatch/ | echo "LALA"
fswatch -o testfswatch/ | someSimpleProgram
fswatch -o testfswatch/ | xargs -n1 -I{} echo "LALA"
fswatch -o testfswatch/ | xargs -n1 -I{} ./someExecutable
fswatch -o testfswatch/ | xargs -n1 echo "LALA"
fswatch -o testfswatch/ | xargs -n1 someExecutable
// And more variations of the above

None of these commands seem to do anything when I change or add files in the tesfswatch/ folder though.

Does anybody know what I'm doing wrong here? All tips are welcome!

Answer

Enrico M. Crisostomo picture Enrico M. Crisostomo · Aug 27, 2014

As already said by Bushmills, fswatch syntax has changed in v. >= 1.x after it was merged with fsw: the rationale behind this decision was allowing more than one path to be watched using a syntax that felt natural to UNIX users.

Furthermore, one specific option (-0) was added to allow easy and non-error-prone piping of fswatch output to another program's input: when using -0, fswatch will separate records using the NUL (\0) character (along the lines of what other utilities such as find and xargs do).

In your case, then, you probably want to use the following syntax (fine tune it according to your needs):

$ fswatch -0 [opts] [paths] | xargs -0 -n 1 -I {} [command]

This way:

  • fswatch -0 will split records using the NUL character.
  • xargs -0 will split records using the NUL character. This is required to correctly match impedance with fswatch.
  • xargs -n 1 will invoke command every command. If you want to do it every x records, then use xargs -n x.
  • xargs -I {} will substitute occurrences of {} in command with the parsed argument. If the command you're running does not need the event path name, just delete this option.

Hope this helps.