It is actually quite easy: you need to write a custom udev rule, which you can place in
/etc/udev/rules.d/10-local.rules
The advantage of doing so is that your custom rule will be read before the other rules.
This file will contain a single line of this form
<conditions to be met> KERNEL=="sd?1", NAME="my_usb_adapter", RUN+="/home/my_name/bin/my_program"
The meaning of this is:
- 'conditions to be met' are a number of conditions, specific to your disk, which identify it uniquely, so that no action is performed when a different HDD is inserted;
- KERNEL=="sd?1" tells udev to start checking this rule only when new partitions /dev/sda1, /dev/sdb1,... are detected. If you need, you can do the same not with a partition, but with the device, in which case KERNEL=="sd?" is the appropriate statement.
- NAME="my_usb_adapter" will create a persistent node at /dev/my_usb_adapter, so that you know where to find the dev to be mounted, if you need to mount it.
- The RUN rule is self-evident. Remember to make
my_program
executable without requiring terminal input or output.
You can obtain the information necessary to perform the matching with the command:
udevadm info -a -p $(udevadm info -q path -n /dev/sdb)
if your disk is /dev/sdb, otherwise modify as you see fit. This will provide a large amount of info. I would search for
ATTRS{idVendor}=="18a5"
ATTRS{idProduct}=="0302"
ATTRS{serial}=="TT0E4E008XW3DT9H"
(these values are for one of my USB dongles, your values will be different). One important caveat: the matching rules must be taken from the same parent device, you cannot mix them.
Now we can write the final rule as:
ATTRS{idVendor}=="18a5", ATTRS{idProduct}=="0302", ATTRS{serial}=="TT0E4E008XW3DT9H", KERNEL=="sd?1", NAME="my_usb_adapter", RUN+="/home/my_name/bin/my_program"
Keep in mind that udev files cannot break lines: if you do, udev will see the broken line as two separate rules. There will be no output to your terminal. Also, I have been quite careful in distinguishing =
, ==
, and +=
: make sure you introduce no mistakes in this.