Friday, December 5, 2008

Running A Script Upon External Disk Removal

A while ago I posted here about how I use a udev rule for triggering the backup of an external USB disk upon being connected to my box.

The udev rule matches both the kernel device name with a wildcard (because it's assigned dynamically) and the device's serial number (which is supposed to be a unique device attribute), and then installs an easy to remember symbolic link to the device and runs the backup script:

KERNEL=="sd?1", ATTRS{serial}=="300000064029", ACTION=="add", SYMLINK+="aluminum", RUN+="/path/to/script"

I now need to run another script when this external USB disk is disconnected.

At first it looked easy enough to accomplish: copy and paste the rule above, replace ACTION=="add" with ACTION=="remove", remove the SYMLINK bit and modify the path to the script.

I was surprised to find out that the script was never called - the remove event did not seem to fire. It took a few anxious minutes, with several physical connects and disconnects of the external disk, before I figured it out.

It seems that when the disk is removed, the conditional ATTRS{serial}==... is always false - presumably because the device attribute called serial is gone and can't be matched against. The correct (read: working) approach is to match against the symbolic link, like this:

SYMLINK=="aluminum", ACTION=="remove", RUN+="/path/to/post/removal/script"

I bet Linus Torvalds drives a car with a manual gearbox.
I guess Bill Gates has a chauffeur.
And Steve Jobs... well, he simply teleports.

No comments:

Post a Comment