Indeed the "remove" action is poorly documented. The caveat is that if you remove the device, the udev system is not able to parse the device attributes anymore, since they are deleted (e.g. the content of /sys/block/sdb is removed).
In this case we can use the udev
environment to run an external script upon removing the usb device. First we can check what environment variables we have at our disposal every time a remove is detected. We can use
udevmonitor --env (on recent releases it shoud be
udevadm monitor --environment --udev):
Code:
# udevmonitor --env
udevmonitor prints the received event from the kernel [UEVENT]
and the event which udev sends out after rule processing [UDEV]
UDEV [1288697550.654831] remove@/block/sdb
UDEV_LOG=3
ACTION=remove
DEVPATH=/block/sdb
SUBSYSTEM=block
SEQNUM=1107
MINOR=16
MAJOR=8
PHYSDEVPATH=/devices/pci0000:00/0000:00:1d.7/usb1/1-3/1-3:1.0/host10/target10:0:0/10:0:0:0
PHYSDEVBUS=scsi
PHYSDEVDRIVER=sd
UDEVD_EVENT=1
ID_VENDOR=JetFlash
ID_MODEL=TS2GJF110
ID_REVISION=0.00
ID_SERIAL=JetFlash_TS2GJF110_69a44ec615507a
ID_TYPE=disk
ID_BUS=usb
ID_PATH=pci-0000:00:1d.7-usb-0:3:1.0-scsi-0:0:0:0
DEVLINKS=/dev/disk/by-id/usb-JetFlash_TS2GJF110_69a44ec615507a /dev/disk/by-path/pci-0000:00:1d.7-usb-0:3:1.0-scsi-0:0:0:0
DEVNAME=/dev/sdb
Here I removed a JetFlash USB stick. As you can see there are a number of udev's environment variables that can uniquely identify my device. Suppose we choose the ID_MODEL, I will write a rule like this:
Code:
ACTION=="remove", ENV{ID_MODEL}=="TS2GJF110", RUN+="/usr/local/bin/test_remove.sh"
Every time ID_MODEL assumes the value "TS2GJF110" the rule is executed and if the ACTION is "remove" the external script /usr/local/bin/test_remove.sh is launched.
There is a chance your script is executed two or more times, depending on how many times the ID_MODEL variable is assigned (as you can see from the output of udevmonitor). In that case you can specify more environment variables until you're sure the device is uniquely identified and the rule is executed only once. For example I can do:
Code:
ACTION=="remove", ENV{ID_MODEL}=="TS2GJF110", ENV{ID_FS_UUID}=="6CE8-0F2C", RUN+="/usr/local/bin/test_remove.sh"
Hope this helps.