How to mount a .sparsebundle after External Hard drive mounts

applescripthard drivemount

I have an external hard drive, with which there is a .sparsebundle that I use for TimeMachine backups. I want to automatically mount this .sparsebundle after the external Drive mounts. I've tried making an AppleScript app to launch on startup, however, it doesn't work. Here is what I have so far.

tell application "Finder"
try
    (mount volume) / Volumes / External
on error
    return
end try

if exists disk "External" then
    do shell script "hdiutil attach /Volumes/External/TimeMachine/TimeMachineTest.sparsebundle"
else
    display dialog "Unable to mount TimeMachine"
end if
end tell

edit:

I made an AppleScript application that mounts the .sparsebundle, but only when its launched. I want this to run whenever the external drive is mounted.

 set mountedVolumes to do shell script "ls /Volumes/"
   if (mountedVolumes contains "External") is true then
     do shell script "hdiutil attach /Volumes/External/TimeMachine/TimeMachineTest.sparsebundle"
 end if

Best Answer

So, I found out a way to do what I wanted via, automator and shell scripts.

I made an Automator Folder Action. set the folder to /Volumes by pressing CMD+SHIFT+G and typing "/Volumes" and adding a Run AppleScript action.

    on run {input, parameters}

set mountedVolumes to do shell script "ls /Volumes/"
if (mountedVolumes contains "External") is true then
    do shell script "hdiutil attach /Volumes/External/TimeMachine/TimeMachineTest.sparsebundle"
end if

return input

That way, when there is an update to the volumes folder, it runs the AppleScript, which mounts the .sparsebundle.

edit:

Found a more simple way.

Create the Folder Action for /Volumes, then add Run Shell Script action.

  hdiutil mount /Volumes/External/TimeMachine/TimeMachineTest.sparsebundle