How to start an application when a specific disk is mounted I store all my music on an external drive.  I have iTunes set to start when I login.  However, iTunes always starts before my encrypted drive has mounted, and so iTunes complains it can't find its library.

I've tried writing an Applescript which repeatedly checks to see if a drive is mounted, and when it is launches iTunes.

tell application "System Events" to set diskNames to name of every disk
set iTunesDiskName to "Media"
set iTunesDiskIsMounted to false
set iTunesLaunched to false
if iTunesDiskName is in diskNames then set iTunesDiskIsMounted to true


repeat while iTunesLaunched is false
    if iTunesDiskIsMounted is true then
        tell application "iTunes" to launch
        set iTunesLaunched to true
    end if
    delay 5
end repeat


This does work to launch iTunes if I run it with the drive mounted. However if I run it with the drive unmounted, it keeps running and never detects if the disk is subsequently mounted.

What am I doing wrong?
I didn't downvote wch1zpink's answer, but it's very much not the way that I would solve the problem.

Having an app run an AppleScript every 5 seconds is a very inefficient way to handle this situation, especially since Mac OS already has a built-in feature to do this, namely, launchd.

Save this as ~/Library/LaunchAgents/com.tjluoma.itunes-on-mount.plist (you can change the "com.tjluoma.itunes-on-mount" part to whatever you want):

&lt;?xml version="1.0" encoding="UTF-8"?&gt;
&lt;!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd"&gt;
&lt;plist version="1.0"&gt;
&lt;dict&gt;
    &lt;key&gt;Label&lt;/key&gt;
    &lt;string&gt;com.tjluoma.itunes-on-mount&lt;/string&gt;
    &lt;key&gt;ProgramArguments&lt;/key&gt;
    &lt;array&gt;
        &lt;string&gt;/bin/bash&lt;/string&gt;
        &lt;string&gt;-c&lt;/string&gt;
        &lt;string&gt;test -d /Volumes/Media &amp;amp;&amp;amp; open -j -g -a iTunes&lt;/string&gt;
    &lt;/array&gt;
    &lt;key&gt;RunAtLoad&lt;/key&gt;
    &lt;true/&gt;
    &lt;key&gt;WatchPaths&lt;/key&gt;
    &lt;array&gt;
        &lt;string&gt;/Volumes&lt;/string&gt;
    &lt;/array&gt;
&lt;/dict&gt;
&lt;/plist&gt;


Then either reboot your Mac or do


launchctl load ~/Library/LaunchAgents/com.tjluoma.itunes-on-mount.plist



in Terminal. Then, anytime /Volumes/ changes, launchd will look to see if /Volumes/Media exists, and if it does, it will launch iTunes.