Run a command when a disk is inserted (Linux)

I would like to automatically run my own command any time a drive is inserted under Linux (including USB drives, for example). Obviously the simplest solution would be to regularly poll and check for changes to /proc/partitions or to /dev/disk, but I was hoping for something a little more elegant than that.

EDIT

I know this is possible, because GNOME does this very thing; any time a new drive is inserted, GNOME runs it's own "autoplay" mechanism to take some action. ("Would you like to view the pictures on this SD card?")

I can come up with two uses for this: the first is in an Amazon EC2 cluster I manage, to detect and initialize newly attached EBS storage volumes automatically.

The other usage is on a Linux-based home file-server device; when I insert an SD card into the device, it should mount the card, move the pictures from the card onto the internal hard drive, unmount the card, and then beep to let me know it's done.


Solution 1:

Udev rules are what you are looking for. From the man page itself:

... If udev receives a device event, it matches its configured rules against the available device attributes provided in sysfs to identify the device. Rules that match may provide additional device information or specify a device node name and multiple symlink names and instruct udev to run additional programs as part of the device event handling. ...

Emphasis mine.

The rules files are in /etc/udev/rules.d/ and their documentation is in udev(7). Oh, and they work for practically everything.

Solution 2:

I found a pretty good link here. http://linlog.skepticats.com/content/udevautorun/

Basically you can place scripts in /etc/udev for all block devices or specific ones.