Auto-mounting USB storage with udev
Auto-mounting external USB devices can be very handy, especially when using headless (no GUI) servers, or in my case a Raspberry Pi. A simple udev script is all that is needed, and assumed that any external storage device connected via USB will need to be mounted automatically in a sub directory of /media
Simply create a file /etc/udev/rules.d/11-media-by-label-auto-mount.rules
with the following:
KERNEL!="sd[a-z][0-9]", GOTO="media_by_label_auto_mount_end"
# Import FS infos
IMPORT{program}="/sbin/blkid -o udev -p %N"
# Get a label if present, otherwise specify one
ENV{ID_FS_LABEL}!="", ENV{dir_name}="%E{ID_FS_LABEL}"
ENV{ID_FS_LABEL}=="", ENV{dir_name}="usbhd-%k"
# Global mount options
ACTION=="add", ENV{mount_options}="relatime"
# Filesystem-specific mount options
ACTION=="add", ENV{ID_FS_TYPE}=="vfat|ntfs", ENV{mount_options}="$env{mount_options},utf8,gid=100,umask=002"
# Mount the device
ACTION=="add", RUN+="/bin/mkdir -p /media/%E{dir_name}", RUN+="/bin/mount -o $env{mount_options} /dev/%k /media/%E{dir_name}"
# Clean up after removal
ACTION=="remove", ENV{dir_name}!="", RUN+="/bin/umount -l /media/%E{dir_name}", RUN+="/bin/rmdir /media/%E{dir_name}"
# Exit
LABEL="media_by_label_auto_mount_end"
Once you have created your script and saved it, reload udev with:
udevadm control --reload-rules
Now, when you connect the USB storage device, udev should automatically create a directory under /media
with either the device ID, or device label (if you have assigned one), and mount the device. If you disconnect the device, the drive directory (in /media
) will be automatically removed.