sword in the stone   Hayne of Tintagel
Mac OS X  /  Programming  /  WatchFile

Watching Files for Changes

OS X applications make use of various support files and these files get read and written quite frequently behind the scenes. Especially when troubleshooting some problem, it is often useful to be notified when relevant files get modified. I wrote a Perl script: 'watchfile' that prints a message when one of the specified files gets modified.

You specify the files or folders you want it to watch in the usual way - as a space separated list on the command-line. For example, if you want it to watch the file ~/Library/Preferences/com.apple.finder.plist, you would run the command:

 % watchfile ~/Library/Preferences/com.apple.finder.plist
Or if you wanted to watch all of the com.apple preference files, you would run the command:
 % watchfile ~/Library/Preferences/com.apple.*
The script will print a message "info stored" when it starts watching each file and then it will check on the file each 10 seconds after that and print a message if anything about the file has changed. The messages are somewhat cryptic, indicating which things have changed since the last check.

Here's a list of the things that might be reported:

Each time a change is reported, the script also shows the result of doing 'ls -ld' on the file or folder.

Command-line Options:

In my testing, I found it very interesting to watch the com.apple preference files, especially with the -atime option. I was surprised how many preference files are being accessed and how often they get written to (and often recreated).

The script should need only small changes to get it to work on other operating systems (anywhere that Perl is installed). It should work as is on any Linux system. After changing the line that does the 'ls -ld', it should even work on Windows if you install Perl.


There are several other programs that watch files for changes.
The well-known application Tripwire occupies a different ecological niche. It is explicitly concerned with security and is far more sophisticated, with concomitant complexity of use.

The Radmind application has a different focus - it is usually used for maintaining multiple machines in a known state.

The bubblegum program is quite similar to the 'watchfile' script in intent but is considerably more sophisticated. It is a compiled C program that is designed to run as a daemon.

The 'watchfile' script was intended mostly for impromptu troubleshooting sessions where the ease of modification of a script (as opposed to a compiled executable) is often a big advantage.

Note: this script was first published as a MacOSXHints article.