Is there a command like "watch" or "inotifywait" on the Mac?

Viewed 152277

I want to watch a folder on my Mac and then execute a bash script, passing it the name of whatever file/folder was just moved into or created in the watched directory.

16 Answers

This is just to mention entr as an alternative on OSX to run arbitrary commands when files change. I find it simple and useful.

  • brew install entr on macos
  • apt install entr on Debian/Ubuntu

I ended up doing this for macOS. I'm sure this is terrible in many ways:

#!/bin/sh
# watchAndRun
if [ $# -ne 2 ]; then
    echo "Use like this:"
    echo "   $0 filename-to-watch command-to-run"
    exit 1
fi
if which fswatch >/dev/null; then
    echo "Watching $1 and will run $2"
    while true; do fswatch --one-event $1 >/dev/null && $2; done
else
    echo "You might need to run: brew install fswatch"
fi

If you want to use NodeJS, you can use a package called chokidar (or chokidar-cli actually) for the watching and then use rsync (included with Mac):

Rsync command:

$ rsync -avz --exclude 'some-file' --exclude 'some-dir' './' '/my/destination'

Chokidar cli (installed globally via npm):

chokidar \"**/*\" -c \"your-rsync-command-above\"

sudo fs_usage -f filesys | grep "interesting thing" ?

I can wholeheartedly recommend using watchexec. Built in Rust and It Just Works™ no matter which platform you're on! Straightforward CLI options as well.

Here's a simple single line alternative for users who don't have the watch command who want to execute a command every 3 seconds:

while :; do your-command; sleep 3; done

It's an infinite loop that is basically the same as doing the following:

watch -n3 your-command

Related