Udev manages devices via rules that determine what to do when a device is inserted (or removed). Udev itself doesn't handle mounting, but you can make it invoke an external program to do the mounting.
There are rules, stored in the various files under /etc/udev/rules.d/
, that create entries in /dev/disk/by-label/
. We can use the same matching conditions to match a USB device which has a filesystem label and run a custom script.
ENV{ID_FS_LABEL_ENC}=="?*", ENV{ID_FS_USAGE}=="filesystem|other", \
SUBSYSTEMS=="usb", \
RUN += "/usr/local/sbin/udev-mount-by-label '%E{ID_FS_LABEL_ENC}'"
The custom script should create the mount point and perform the mounting. It should take a bit of care in case the directory already exists. The script I've written will do nothing if the mount point is already in use as a mount point, but will happily shadow a non-empty directory. Customize to your taste.
#!/bin/sh
export mount_point="/media/$1"
current_device=$(awk '$2 == ENVIRON["mount_point"] {print $1; exit}' </proc/mounts)
if [ -n "$current_device" ]; then
echo 1>&2 "$current_device already mounted on $mount_point"
exit 1
fi
mount "/dev/disk/by-label/$1" "$mount_point"
Don't forget to unmount the device before unplugging it, otherwise you may lose data.
Ubuntu - Automatically mount external drives to /media/LABEL on boot without a user logged in? shows the same technique with a different script.
udev
rules.blkid
with the USB attached.