5

In OS X, is there a way (shell script-ish?) to watch a directory for a file pattern and if there are any file changes to execute a command?

1
  • Although not needed, it might help to have an example: Which files do you want to watch and what should be done with them? Are you limited to using the command line or can you use AppleScript as well?
    – slhck
    Jul 8, 2011 at 10:54

2 Answers 2

4

There's an app for that:

/System/Library/CoreServices/Folder Actions Setup.app

Select a folder to watch and a script to be executed. You can also edit the script.

5

~/Library/LaunchAgents/watch.and.lol.plist:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
    <key>Label</key>
    <string>watch.and.lol</string>
    <key>ProgramArguments</key>
    <array>
        <string>say</string>
        <string>lol</string>
    </array>
    <key>WatchPaths</key>
    <array>
        <string>~/Desktop</string>
    </array>
</dict>
</plist>

launchctl load ~/Library/LaunchAgents/watch.and.lol.plist or relogin to load the agent.

There's a launchd gotcha « Managing OS X though:

It turns out that if a file is listed as a launchd job WatchPath, it must exist at all times, or launchd removes the path from its list of paths to watch. So you can't watch for the creation of a certain file; you can only watch for changes to the file.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .