Per Stenebo
2015-01-27 20:27:28
2017-04-16 12:59:15
udev and automount
Hotplug a USB drive to a Raspberry Pi, mount it on the filesystem, do something and then unmout it again.
There are other methods if you are just looking for a way to automount/hotplug a usb drive, like autofs and such.
But this udev stuff is useful if you want to do something specific after the drive have been attached.
udev rule
Attach the USB drive and check what device file the partition got, it should be something like "/dev/sda1":
sudo fdisk -l
Check device properties on the given device file:
sudo udevadm info -q path --attribute-walk -n /dev/sda1
Create and edit the udev rule file:
sudo nano /etc/udev/rules.d/usbdrive.rules
Add the rules, use suitable parameters from udevadm output, like:
ACTION=="add", SUBSYSTEMS=="usb", RUN+="/usr/local/bin/usbdrive.sh"
To make the rule run the script only once I had to modify the rule like this (ENV{DEVTYPE}=="usb_device" is not in udevadm output):
ACTION=="add", SUBSYSTEMS=="usb", ENV{DEVTYPE}=="usb_device", RUN+="/usr/local/bin/usbdrive.sh"
The rule above should apply to any usb drive, if you want to bind it to a specific device you can use a line like:
ACTION=="add", SUBSYSTEMS=="usb", ENV{DEVTYPE}=="usb_device", ATTRS{serial}=="00D0C9CCDF4DEBB180004553", RUN+="/usr/local/bin/usbdrive.sh"
Create and edit a shell script:
sudo nano /usr/local/bin/usbdrive.sh
Add a simple debug command, the output can later be read in /var/log/syslog:
#!/bin/bash
logger "${0} started | ACTION: ${ACTION}"
Make the script executable:
sudo chmod +x /usr/local/bin/usbdrive.sh
Reboot to let the udev rule file take effekt. Then the rule file content can be edited with immediate effect.
Insert a USB drive and check the end of syslog:
tail /var/log/syslog
There might be several similar entries indicating that the script was actually run several times. This can be adressed by being more specific in the udev rule or handle it in the script.
This can aid in troubleshooting, execute the command, insert your drive and monitor output:
udevadm monitor --udev
mount script
If the udev rule resulted in the expected line in syslog we can continue to edit the script. In this script we can do just about anything, but now I just mount the connected drive. You find the script here.