Automount USB devices on Linux using UDEV and Systemd
I’ve already talked about my GNU/Linux workstations: my setup is often minimal and without graphical facilities.
However, some facilities can be replicated without graphical tools and with a very small footprint on the system.
For example, on my setup i’ve realized a USB automount service without using any external tool/service, with only udev and systemd.
The first step is a brief shell script, which will be called by systemd and takes care of creating and removing mount points, and mounting and unmounting the drives:
Just create this file in /usr/local/bin/usb-mount.sh and set +x permissions. The script also sends a desktop notification to the user:
(this part needs and additional configuration with username and userid,line 47)
In order to allow systemd to call this script, we need to create a unit file.
So create the file /etc/systemd/system/[email protected] with the following content:
[Unit] Description=Mount USB Drive on %i [Service] Type=oneshot RemainAfterExit=true ExecStart=/usr/local/bin/usb-mount.sh add %i ExecStop=/usr/local/bin/usb-mount.sh remove %i
(we use the “@” filename syntax so we can pass the device name as an argument)
Finally, a couple of udev rules to start and stop the systemd unit service on hotplug/unplug (create a new file in /etc/udev/rules.d/99-local.rules):
KERNEL=="sd[a-z][0-9]", SUBSYSTEMS=="usb", ACTION=="add", RUN+="/bin/systemctl start [email protected]%k.service" KERNEL=="sd[a-z][0-9]", SUBSYSTEMS=="usb", ACTION=="remove", RUN+="/bin/systemctl stop [email protected]%k.service"
In order to enable the configuration, reboot the system or call this commands:
# udevadm control --reload-rules # systemctl daemon-reload