A Perl script to watch files for changes

Oct 01, '03 10:34:00AM

Contributed by: hayne

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 (which I call watchfile [4kb download from macosxhints.com]) that prints a message when one of the specified files gets modified. As usual, you need to make the script file executable (with chmod +x) and install the script in a folder that is in your shell's execution path.

You execute this script in a Terminal window, specifying the file or files you want it to watch in the usual way (a space-separated list of filenames). 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. Read the rest of the hint for a breakdown on the messages you might see...

[robg adds: I tried this script, and it's really pretty interesting. It's amazing to see how much stuff is changed, and how often it's changed.]

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 -l on the file.

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).

One final note: Although I haven't yet tried it, I think 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 -l, it should even work on Windows if you install Perl.

Comments (22)


Mac OS X Hints
http://hints.macworld.com/article.php?story=20031001073403810