Automatically run script when a volume mounts?

I wold like to know how to make a script I have created run when I plug in my external hard drive. Right now I have it set that a certain file is copied to the disk whenever I open the folder. However, I don’t need it running each time I open the folder, I would rather it run just when the volume mounts. Does anyone know how to do this? Thanks

on opening folder this_folder
	activate application "Matt's Mac:Users:mattbasile:Library:Workflows:Applications:Folder Actions:Diabetes Log"
end opening folder

Model: MacBook Core Du0
AppleScript: 1.0
Browser: Safari 525.13
Operating System: Mac OS X (10.4)


take a look at Craig Smith’s article Using launchd with AppleScript to Access a Flash Drive Automatically
It works also with hard drives.

thanks, I’ll give all of that stuff a read on the morning, it’ll probably be over my head even then anywas

I have come across question in this thread many times.

The answers I’ve found so far boil down to 2 options: 1) use launcd for monitoring, 2) use stay-open app for monitoring.

Both answers do not quite correspond to the real monitoring of the “certain disk connected” event, so my question is this:

Has anyone tried making the /Volumes folder a “hot” folder and assigning a script to it? I think it should work like a real monitor

I decided to test my guess, and made the “/Volumes” folder a “hot” folder (aka folder action). Then, I attached the following script to it:

on adding folder items to this_folder after receiving these_items
	set volumeName to name of (get info for (item 1 of these_items)) as Unicode text
	display notification "Disk \"" & volumeName & "\" inserted"
end adding folder items to

It looks like I can congratulate myself and others that my hunch was correct.

Because as soon as I plug in one of my flash drives, the display notification automatically fires up and notifies me that a drive is inserted, and also informs me of its name.

In the same way, you can register the disk removal event by applying the “on removing…” handler.

Refer to the run in background AppleScript

Some time ago I did something like that, and actually prepared 2 options:
1 – using folder actions, it works fine. I posted this option on the blog, if you are interested, you can look at my “rough” code. :slight_smile:
2 – Then I rewrote everything, because in one example, thanks to you, I understood how to handle handlers. Use User Agent in Launchd,

--Имя съёмного раздела раздела
set RemovableDiskName to "Flash"
set SyncRootFolder to "Портфель"
--Ищем имя съёмного раздела среди всех подключенных 
tell application "System Events" to set MountedDisks to name of every disk
if RemovableDiskName is in MountedDisks then
	--Перечисляем каталоги, которые необходимо синхронизировать с съёмным накопителем
	set SyncFolders to {¬
		"Проект А", ¬
		"Проект Б", ¬
		"Инструкции тех. поддержки", ¬
	repeat with SyncFolder in SyncFolders
		my StartSync(SyncRootFolder, SyncFolder, RemovableDiskName)
	end repeat
	--Раскомментировать, если необходимо отключать носитель после завершения синхронизации
	--my UnmountDisk(RemovableDiskName)
end if
--Обработчик синхронизации
on StartSync(SyncRootFolder, SyncFolder, RemovableDiskName)
	set SourcePath to quoted form of (POSIX path of (path to documents folder as text) & SyncRootFolder & "/" & SyncFolder & "/")
	tell application "System Events" to set DestinationPath to quoted form of (POSIX path of disk item RemovableDiskName & "/" & SyncFolder as text)
		do shell script "rsync -au --delete" & space & SourcePath & space & DestinationPath
		delay 1
		display notification "Каталог" & space & quoted form of SyncFolder & space & ¬
			"синхронизирован с съёмным диском" & space & RemovableDiskName with title "Синхронизация каталога"
	on error ErrorMessage
		set ErrorMessage to do shell script "echo" & space & quoted form of (ErrorMessage as text) & "| awk -F 'failed:' '{print$2}' | awk -F ' at ' '{print$1}'"
		display dialog "Копирование каталога" & space & quoted form of SyncFolder & space & "не выполнено." & ¬
			return & "Failed:" & space & ErrorMessage buttons {"OK"} default button 1 with icon stop
	end try
end StartSync
--Обработчик размонтрования накопителя
on UnmountDisk(RemovableDiskName)
	delay 5
	tell application "Finder" to eject RemovableDiskName
end UnmountDisk

After saving the script, you need to create an xml daemon

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "">
<plist version="1.0">

The daemon will start automatically every time after mounting any disk.

It remains to start the daemon

launchctl load -w ~/Library/LaunchAgents/custom.sync.flash.plist

And connect flash drive.

I like the second option better. Because here I will add error handling, and the code seems clearer with handlers.

1 Like

Another option would be to use EventScripts. I believe it can be configured to execute an AppleScript every time a volume is mounted.