5

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.

1
  • 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. Apr 17, 2010 at 22:32

1 Answer 1

6

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">
  <dict>
    <key>Label</key>
    <string>net.stuff-things.backup-to-dropbox</string>
    <key>ProgramArguments</key>
    <array>
      <string>/Users/spike/bin/backup-to-dropbox</string>
    </array>
    <key>StartOnMount</key>
    <true/>
  </dict>
</plist>
1
  • 1
    URL is no longer correct
    – emmby
    Jun 3, 2016 at 17:16

You must log in to answer this question.

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