11

I am trying to get a script to run whenever ANY USB flash drive (not just a specific one) is plugged in to the system and I have been pulling my hair out for about 2 weeks now on and off trying to figure it out. Can anybody help me? (running Ubuntu if that helps).

I need to be able to pass the drive serial number and the devpath (/dev/sd**) at bear minimum.

Kara
  • 5,650
  • 15
  • 48
  • 55
smd75jr
  • 127
  • 1
  • 1
  • 6
  • possible duplicate of [How do I detect usb drive insertion in Linux?](http://stackoverflow.com/questions/8190542/how-do-i-detect-usb-drive-insertion-in-linux) – Jim Garrison Nov 20 '13 at 00:19
  • not a duplicate, the other question involves QT/libudev (ie, C programming). This seems more of bash script issue. – SpliFF Nov 20 '13 at 01:51

1 Answers1

14

First you need your rule to detect usb storage devices

/etc/udev/rules.d/10-usbmount.rules:

KERNEL=="sd*[!0-9]|sr*", ENV{ID_SERIAL}!="?*", SUBSYSTEMS=="usb", RUN+="/usr/bin/usbdevinserted"

This runs our custom executable shell script /usr/bin/usbdevinserted:

#!/bin/bash

set 2>&1 >> /tmp/usbdevinfo

This sample script dumps the environment variables which you will need to know which device was found, eg:

DEVLINKS='/dev/disk/by-id/usb-Generic_USB_Flash_Disk-0:0 /dev/disk/by-path/pci-0000:00:13.2-usb-0:2:1.0-scsi-0:0:0:0'
DEVNAME=/dev/sdk
DEVPATH=/devices/pci0000:00/0000:00:13.2/usb2/2-2/2-2:1.0/host29/target29:0:0/29:0:0:0/block/sdk
DEVTYPE=disk
ID_BUS=usb
ID_FS_TYPE=
ID_INSTANCE=0:0
ID_MODEL=USB_Flash_Disk
ID_MODEL_ENC='USB\x20Flash\x20Disk\x20\x20'
ID_MODEL_ID=9380
ID_PART_TABLE_TYPE=dos
ID_PART_TABLE_UUID=61d1df0b
ID_PATH=pci-0000:00:13.2-usb-0:2:1.0-scsi-0:0:0:0
ID_PATH_TAG=pci-0000_00_13_2-usb-0_2_1_0-scsi-0_0_0_0
ID_REVISION=7.76
ID_SERIAL=Generic_USB_Flash_Disk-0:0
ID_TYPE=disk
ID_USB_DRIVER=usb-storage
ID_USB_INTERFACES=:080650:
ID_USB_INTERFACE_NUM=00
ID_VENDOR=Generic
ID_VENDOR_ENC='Generic\x20'
ID_VENDOR_ID=058f
MAJOR=8
MINOR=160
SUBSYSTEM=block
gioele
  • 8,311
  • 4
  • 49
  • 75
SpliFF
  • 35,724
  • 15
  • 80
  • 113
  • 1
    The redirection in the bash script should be `2>&1`. Currently it creates a file named "1" while I suppose stdout (file descriptor 1) was meant. – Aki Koskinen Oct 01 '16 at 11:17