Detect Pen Drive Insertion

After having lost my pen drive and gone through quite a bit to get it back, I’ve become somewhat paranoid about keeping a duplicate of it. So, basically, I’m trying to write something to, when it is plugged in, mount it and run rsync to keep a copy of its contents. I have two main problems:

  1. There has to be a better way to detect insertion than polling the syslog or the contents of /dev. What is the right way to wait for a device insertion?
  2. How can I uniquely identify the device? I can easily get the vendor ID and device ID, but that only limits it to the model of pen drive, not a specific one.

Less important, but is there any way I can hook umount to sync prior to unmounting the device?

Any help would be appreciated.

I can help point you in the right direction. Essentially, you can write a udev rule that can uniquely be matched against a number of specific device attributes (when device is inserted), and then run a particular script for example. A couple of useful tutorials to give you an idea:

Writing udev rules

How to write udev rules - Hack a Day

a better way to detect insertion
:wink:

Just give your pen drive a volume label… Eg: My_Drive

Every time it mounted it will be as My_Drive

It works beautifully.

Edit: Sorry, I thought I wanted to add something, but it is all there allready.

It looks like I can do most of what I want on insertion with udev. Does anyone know of any way to hook umount?

That is more difficult because while the cascade of actions resulting in a mount is triggered by electrical currents at drive insertion, the umount must be triggered by the electrical currents in the mind of the user when he thinks: “enough!”

It looks like I can do most of what I want on insertion with udev. Does anyone know of any way to hook umount?

Not sure what you’re trying to achieve here. Like Henk mentioned, simply removing the device will render any following useful system action too late. Manually unmounting is the norm, before removing the external storage device.

Similar discussion here:

How to automount USB pendrive and CD/DVD, using udev/HAL/D-BUS | debianHELP