How do i autorun .command files from a USB drive when I plug it in

terminalusb

I've made two .command files, "lock" and "unlock". The first hides hidden files with: defaults write com.apple.Finder AppleShowAllFiles TRUE, then refreshes finder with killall Finder. The second does the opposite, I simply replaced TRUE with FALSE, in the first command.

I'd like to copy these over to a USB thumb drive in such a way that when I plug this USB into my laptop, it automatically executes the "unlock" file, and as soon as I unplug it, the "lock" file is executed.

I don't know to what extent this is possible and what drawbacks/problems it may entail, but any help or input is very much appreciated. I'm also only doing this for fun, so I'm perfectly okay with experimenting!

Best Answer

A launchd service supports the WatchPaths option, which launches a program when the contents of a folder are changed:

WatchPaths <array of strings> This optional key causes the job to be started if any one of the listed paths are modified.

By watching /Volumes, a shell script can be created which would check whether your external disk is mounted or not° and run the appropriate commands°°.

° The simplest way would be checking for the presence of a /Volumes/disk-name/ folder, but it would also be the simplest to fool with by renaming the partition or having another one with the same name, causing the mount point to be modified.

°° It would be appropriate to use a temporary file storing the result of the last execution to avoid killing the Finder if another disk was to be [un]mounted.