Run script when USB Stick is mounted

raspberrypi3

#1

Hi,

I want to run a script when I plug in an USB stick. The script mounts the USB drive, reads a file from the drive, does some config work and unmounts the device.

I tried to do it with udev by creating the following rule in /etc/udev/rules.d/udev-plug-usb.rules

ACTION=="add", SUBSYSTEM=="usb", RUN+="touch /usr/src/app/success"

(for testing purpose, I only want to create a file success. The script itself would mount the stick and do it’s work.)

However, this doesn’t work. I tried to reload the rules

udevadm control --reload-rules && udevadm trigger

but this didn’t have any effect. Then I integrated the file in my Dockerfile, and reboot the device, nothing changed.

When I log at the monitor with udevadm monitor --env and I plug in my usb stick, I get a lot of logs like this:

KERNEL[7842.430544] add      /devices/platform/soc/3f980000.usb/usb1/1-1/1-1.3 (usb)
ACTION=add
BUSNUM=001
DEVNAME=/dev/bus/usb/001/015
DEVNUM=015
DEVPATH=/devices/platform/soc/3f980000.usb/usb1/1-1/1-1.3
DEVTYPE=usb_device
MAJOR=189
MINOR=14
PRODUCT=13fe/4200/100
SEQNUM=7609
SUBSYSTEM=usb
TYPE=0/0/0

So my questions are:

  1. Why does the touch not fire when I plug in my USB Stick?
  2. Is there an easier way to run a script when an USB stick is plugged in (any stick, not a specific one)?

#4

In the interests of asking silly questions rather than making silly assumptions, does this same process work fine in a non-IoT OS, for example Raspbian?


#6

Hi,
You need to use the full path to the touch binary. I tested the following setup:

Add file /etc/udev/rules.d/usb-plug.rules with contents:

ACTION=="add", SUBSYSTEMS=="usb", RUN+="/usr/bin/touch /usr/src/app/success"

Run:

udevadm control --reload-rules && udevadm trigger

Now, when I plug in a USB stick it creates the file /usr/src/app/success.

Cheers,
Andreas