Automount USB disks in Linux#

227 words | 3 min read


I installed Ubuntu server 23.10 on one of my computers very recently, and ran into a surprising problem that…in 2023, USB mounting and unmounting does not happen automatically in Linux.

I didn’t want to be creating entries in /etc/fstab for every disk I have (or might acquire in future). I needed a simpler plug-and-play solution. A lot of Google searching pointed me to udev, but I could not find a single script that met my needs.

After quite a bit of searching and reading, I stumbled upon this post from the odroid.com forum. However, user alpe’s solution has a slight problem in that his (or her) solution uses mount in the udev rule.

The systemd developers apparently recommend the use of systemd-mount in udev rules.

Fortunately, it was relatively easy to incorporate systemd-mount and systemd-unmount in place of mount and unmount. I tested this rule successfully on both Ubuntu server 23.10 and 23.04.

This udev rule will automatically mount the disk in a subdirectory under /media (either by the disk label or by UUID). And it will also remove the mount point once the disk is unplugged. Here are the steps to get it working:

1. create /etc/udev/rules.d/99-automount-usb.rules#

Note

You will need root privileges to create the udev rule.

/etc/udev/rules.d/99-automount-usb.rules#
KERNEL!="sd*", GOTO="media_by_label_auto_mount_end"
ENV{ID_TYPE}!="disk", GOTO="media_by_label_auto_mount_end"
# Import FS infos
IMPORT{program}="/sbin/blkid -o udev -p %N"
ENV{ID_FS_TYPE}=="", GOTO="media_by_label_auto_mount_end"
ENV{ID_FS_LABEL}!="", ENV{dir_name}="%E{ID_FS_LABEL}"
ENV{ID_FS_LABEL}=="", ENV{dir_name}="%E{ID_FS_UUID}"

ACTION=="add", SUBSYSTEMS=="usb", SUBSYSTEM=="block", ENV{ID_FS_USAGE}=="filesystem", RUN{program}+="/usr/bin/systemd-mount --no-block --automount=yes --collect /dev/%k /media/%E{dir_name}"
#
# Clean up after removal
ACTION=="remove", SUBSYSTEMS=="usb", SUBSYSTEM=="block", ENV{ID_FS_USAGE}=="filesystem", ENV{dir_name}!="", RUN{program}+="/usr/bin/systemd-umount /media/%E{dir_name}", RUN{program}+="/bin/rmdir /media/%E{dir_name}"
# Exit
LABEL="media_by_label_auto_mount_end"

2. Reload the udev rule(s)#

Reload udev rule(s)#
$ sudo udevadm control --reload

3. Request device events from the kernel#

Request device events from the kernel#
$ sudo udevadm trigger

Linux should now automagically recognize USB disks when they are plugged in!

Comments

Comments powered by giscus, use a GitHub account to comment.