Skip to content

Instantly share code, notes, and snippets.

@juancarlospaco
Last active October 17, 2022 15:16
Show Gist options
  • Star 7 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save juancarlospaco/7f4eab1b6899c55ea90dc0ef5eea965d to your computer and use it in GitHub Desktop.
Save juancarlospaco/7f4eab1b6899c55ea90dc0ef5eea965d to your computer and use it in GitHub Desktop.
UDev rule that auto mounts any hot-plugged device under /media/<label> and works seamlessly with vfat, ntfs, etc USB storages on Arch Linux. Paste this file and reboot:
# /etc/udev/rules.d/10-my-media-automount.rules
# start at sdb to ignore the system hard drive
KERNEL!="sd[b-z]*", GOTO="my_media_automount_end"
ACTION=="add", PROGRAM!="/sbin/blkid %N", GOTO="my_media_automount_end"
# import some useful filesystem info as variables
IMPORT{program}="/sbin/blkid -o udev -p %N"
# get the label if present, otherwise assign one based on device/partition
ENV{ID_FS_LABEL}!="", ENV{dir_name}="%E{ID_FS_LABEL}"
ENV{ID_FS_LABEL}=="", ENV{dir_name}="usbhd-%k"
# create the dir in /media and symlink it to /mnt
ACTION=="add", RUN+="/bin/mkdir -p '/media/%E{dir_name}'"
# global mount options
ACTION=="add", ENV{mount_options}="relatime"
# filesystem-specific mount options (777/666 dir/file perms for ntfs/vfat)
ACTION=="add", ENV{ID_FS_TYPE}=="vfat|ntfs", ENV{mount_options}="$env{mount_options},gid=100,dmask=000,fmask=111,utf8"
# automount ntfs filesystems using ntfs-3g driver
ACTION=="add", ENV{ID_FS_TYPE}=="ntfs", RUN+="sudo mount -t ntfs-3g -o %E{mount_options} /dev/%k '/media/%E{dir_name}'"
# automount all other filesystems
ACTION=="add", ENV{ID_FS_TYPE}!="ntfs", RUN+="sudo mount -t auto -o %E{mount_options} /dev/%k '/media/%E{dir_name}'"
# clean up after device removal
ACTION=="remove", ENV{dir_name}!="", RUN+="/bin/umount -l '/media/%E{dir_name}'", RUN+="/bin/rmdir '/media/%E{dir_name}'"
# exit
LABEL="my_media_automount_end"
@juancarlospaco
Copy link
Author

sudo chmod +x /etc/udev/rules.d/10-my-media-automount.rules
sudo pacman -S ntfs-3g
sudo mkdir /mnt/
sudo chmod 777 /mnt/
sudo reboot now

@og900aero
Copy link

Doesn't work for me on Arch + bspwm

@og900aero
Copy link

og900aero commented Nov 17, 2020

Works with this command:

ACTION=="add", ENV{ID_FS_TYPE}!="ntfs", RUN+="/usr/bin/systemd-mount --no-block --automount=yes --collect /dev/%k '/media/%E{dir_name}'"

@marcoc1712
Copy link

does this works with NTFS disks?

In my debian 10 it correctly mounts the partition in th folder (df shows the space is used, but no files are showed inside the folder.
The same command issued at the bash prompt it works.

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