Monitor files and directory content changes on Mac

Subscribe Send me a message home page tags


In this post, we describe how we can use fswatch tool to monitor files or directory content changes. This is useful when we are editing files that are inputs of downstream processes.

The common usage is provided in the code below. We just need to specify the directory and the files to monitor in the script. We also need to provide the command to be executed when a change is detected. Of course, Of course, there is always room for improvement. We can make directoryToMonitor, fileToMonitor and commandToExecute parameters. Action triggers (in our case it's a if statement) can also be generalized.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#!/bin/bash

directoryToMonitor="";
fileToMonitor="";

echo "start monitoring path: ${directoryToMonitor}.";

fswatch ${directoryToMonitor} | while read change;

do
    echo -e "\n[$(date)] ${change}";
    fileName=$(basename ${change});
    dirName=$(dirname ${change});

    if [[ "${filename}" == ${fileToMonitor} ]]; then
        commandToExecute;
    fi
done

----- END -----

Welcome to join reddit self-learning community.
Send me a message Subscribe to blog updates

Want some fun stuff?

/static/shopping_demo.png