Skip to content

Instantly share code, notes, and snippets.

@magnetikonline
Created March 3, 2024 05:39
Show Gist options
  • Save magnetikonline/ba4ef58f09cb8de4410d91e01219a01a to your computer and use it in GitHub Desktop.
Save magnetikonline/ba4ef58f09cb8de4410d91e01219a01a to your computer and use it in GitHub Desktop.
macOS execute command upon directory change via launchd.

macOS execute command upon directory change via launchd

Using launchd to watch a filesystem directory and upon create/change to a file with the directory, execute a command.

Install

For this example:

  • Watching directory of: /path/to/watch.
  • Upon file change, execute: /path/to/command argument1 argument2.

Copy, or symlink example.plist under the directory $HOME/Library/LaunchAgents:

$ ln -fs "./example.plist "$HOME/Library/LaunchAgents"

Load example.plist into launchd:

launchctl load "$HOME/Library/LaunchAgents/example.plist"

The example.plist can be removed by running:

launchctl unload "$HOME/Library/LaunchAgents/example.plist"

then deleting example.plist.

Related

<?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>example.watcher</string>
<key>ProgramArguments</key>
<array>
<string>/path/to/command</string>
<string>argument1</string>
<string>argument2</string>
</array>
<key>WatchPaths</key>
<array>
<string>/path/to/watch</string>
</array>
</dict>
</plist>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment