Skip to content

Instantly share code, notes, and snippets.

@RafaelPalomar
Last active May 20, 2023 22:40
Show Gist options
  • Save RafaelPalomar/acdd719f4e491756663a05ff6652c0f0 to your computer and use it in GitHub Desktop.
Save RafaelPalomar/acdd719f4e491756663a05ff6652c0f0 to your computer and use it in GitHub Desktop.
Automount USB external drives with udev rules and systemd workaround #udev #automount #usb #systemd #gentoo

Automount USB external drives with udev rules and systemd workarounds

Generate /etc/udev/rules.d/11-media-by-label-auto-mount.rules with the following content

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"

Open /lib/systemd/system/systemd-udev.service

Replace PrivateMount=yes –> PrivateMount=no

Add MountFlags=shared in the [service] section

Remove SystemCallFilter=@system-service @module @raw-io

Restart systemd-udevd service

Alternative (not tried)

https://www.andreafortuna.org/2019/06/26/automount-usb-devices-on-linux-using-udev-and-systemd/

@kcris
Copy link

kcris commented May 20, 2023

seems like the "right way" is to avoid using mount inside udev rules

and use systemd-mount instead

https://wiki.archlinux.org/title/Udev#Mounting_drives_in_rules

@RafaelPalomar
Copy link
Author

Thanks for the tip @kcris

@kcris
Copy link

kcris commented May 20, 2023

thank you! your script was useful!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment