How do I run a script when a drive is mounted under OSX?

My usecase is that I would like to automatically copy images from my USB memory/harddrive when it is inserted in my USB card reader, and when a DVD or CD is inserted I would like to copy it for storage in my media center.

I've tried using Marco Polo (as mentioned in this related question) but from what I can see it can only detect the presence of a certain USB device, not the presence of specific harddrive.

  • But you can run an arbitrary script with Macro Polo. Your script can then detect the presence of the particular volume you're interested in? If Marco Polo still isn't for you, see my answer on writing a Launch Daemon, which is probably essentially what Macro Polo is doing anyway. – Steve Folly Apr 17 '10 at 22:32

You could write a user launch daemon which runs when a filesystem is mounted. The thread here http://forums.macosxhints.com/archive/index.php/t-89968.html should help you get started.

You'll need to write a launchd plist which runs a script when any filesystem is mounted. Your script should then check that the volume you're interested in has been mounted and then do whatever it needs to do.

Do you need this to run as root or as a user? That will determine whether your plist goes into /Library/LaunchDaemons or ~/Library/LaunchDaemons. If the latter, it will only run when the user is logged in.

UPDATE - emmby pointed out the URL is no longer valid. In summary, you need to use the StartOnMount key in your launch daemon. For example (copied from http://stuff-things.net/2015/03/18/backups-with-rsync-and-launchd/ ):

<?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">
  • I got it working with a launchd script - thanks! – Max Rydahl Andersen Apr 24 '10 at 13:43
  • 1
    URL is no longer correct – emmby Jun 3 '16 at 17:16

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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