Example: Writing a Launch Agent for Apple's launchd

Example: Writing a Launch Agent for Apple's launchd

Clutter in programmer workspaces, whether digital or physical, add a mental cost. An area of common clutter is the ~/Downloads directory in Mac OS X. I want to clean it up… programmatically.

The Goal

I want a background job to find files in ~/Downloads which haven’t been modified within the past week and move them into ~/.Trash. In zsh, we do:

mv ~/Downloads/*(mw+1) ~/.Trash

Read man zshexpn for more awesomeness on shell expansion.

Launch Agents

For a user-specific background job, Apple recomends creating a Launch Agent, which is a .plist XML file located in ~/Library/LaunchAgents.

~/Library/LaunchAgents/com.thoughtbot.cleandownloads.plist will run my script once an hour:

<?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">
    <string>~/Downloads/*(mw+1) ~/.Trash</string>

Read Creating Launch Daemons and Agents for more on how to structure the .plist file.

Adarsh Pandit Developer

Hound reviews Ruby and CoffeeScript code for style violations and comments on your GitHub pull requests. Free for open source repos.