Take the 2-minute tour ×
Super User is a question and answer site for computer enthusiasts and power users. It's 100% free, no registration required.

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?

share|improve this question
    
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 '11 at 10:54

2 Answers 2

up vote 4 down vote accepted

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.

share|improve this answer

~/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.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.