OS X: Running a script when a USB drive is inserted

I rsync all my data to a USB drive that I keep at work. I wanted a way to have my rsync script automatically run when I plugged in the drive – kinda like Time Machine.

It ended up being pretty simple. All I needed to do is create and AppleScript and attach it to a “Folder Action” for the /Volumes folder. This script below is launched when a new item is added to the /Volumes folder, i.e. when you insert a new volume. This script will try to run a BASH script if it exists on that volume (.OnInsert)

on adding folder items to this_folder after receiving these_items
	repeat with current_item in these_items
		try
			do shell script POSIX path of current_item & ".OnInsert"
		end try
	end repeat
end adding folder items to

Save this as a .scpt file and put it in ~/Library/Workflows/Applications/Folder\ Actions folder.
Next, right click the /Volumes folder and select Services -> Folder Action Setup and attach the script you just created
AutoMagic!

, ,

3 Responses to OS X: Running a script when a USB drive is inserted

  1. Tcheva November 23, 2013 at 3:04 am #

    Hi JB,

    First thanks for you explanations. I’m trying to execute a simple script when i plug an usb key. I have followed the steps but it doesn’t work for me 🙁

    Here is my script (hitkey.sh) that i put in the volumes folder :

    #!/bin/sh
    # A simple script that simulates hitting the key specified on OS X

    echo “tell application \”System Events\” to keystroke \”Hello World\”” | osascript

    I have also replaced the name of the script (.OnInsert by .hitkey) and attached the above script by services on my usb key.

    Have you any idea?

    Regards,

    Tcheva

  2. Chris September 15, 2015 at 11:41 am #

    Thanks for this!

  3. Martin January 17, 2016 at 7:17 pm #

    do shell script POSIX path of current_item & “.OnInsert”
    should be
    do shell script POSIX path of current_item & “/.OnInsert”