Running a script after inserting USB flash drive

I needed the ability to run a bash script after inserting a USB flash drive into a debian box. This can quite easily be achieved using UDEV rules.

First I ran
cat /proc/scsi/usb-storage/*
Host scsi2: usb-storage
       Vendor: Kingston
      Product: DT 101 G2
Serial Number: 001CC07CED72F05089161312
     Protocol: Transparent SCSI
    Transport: Bulk
       Quirks:
The field that’s important in this output is the serial number as
it will be unique and thus you can have rules that run depending on
which device is inserted.
I created the file
/etc/udev/rules.d/usbflash.rules (Since it is not prefixed by a
number it is ran last by udev) and added the following (THIS CODE IS
ONLY HERE FOR REFERENCE AND DOES NOT WORK, READ FULL POST)
SUBSYSTEMS=="usb", ATTRS{serial}=="001CC07CED72F05089161312", SYMLINK+="Kingston101", RUN+="/full/path/to/script.sh"

Save and exit

I tried to reload the udev rules using

sudo udevadm control –reload-rules

however got the following error unrecognized command ‘reload-rules’ so had to do /etc/init.d/udev restart instead

Make sure you chmod +x your bash script

Now when you insert your flash drive your script should run.

Update: I found the script ran 7 or 8 times after the device was
inserted. I looked into the UDEV rule and added SUBSYSTEM=="block" on
next insertion it only ran twice. 

After running udevadm monitor –udev I found it was running once per ‘block’

UDEV  [1384285043.601207] add      /block/sde (block)
UDEV  [1384285043.648162] add      /block/sde/sde1 (block)

So I added an extra bit to the udev rule to only run it when it detects partition 1

KERNEL=="sd[a-z]1"

SO THE FULL WORKING CODE IS

SUBSYSTEMS=="usb", SUBSYSTEM=="block", KERNEL=="sd[a-z]1",
ATTRS{serial}=="001CC07CED72F05089161312", ACTION=="add",
SYMLINK+="Kingston101", RUN+="/full/path/to/script.sh"

You may also like

Leave a Reply

Your email address will not be published. Required fields are marked *