Skip to content

Instantly share code, notes, and snippets.

@hh10k
Last active January 1, 2016 07:09
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hh10k/8110143 to your computer and use it in GitHub Desktop.
Save hh10k/8110143 to your computer and use it in GitHub Desktop.
udev script and rules for automounting a disk under /media/ with its label
#!/bin/bash
# This file goes in /lib/udev/storage.sh
# Based on http://superuser.com/a/630937
# A matching /etc/udev/rules.d/85-storage-automount.rules should contain:
# ENV{DEVTYPE}=="partition", ENV{DEVNAME}!="/dev/mmcblk0p?", PROGRAM="/lib/udev/storage.sh mountpoint", ENV{MOUNTPOINT}="$result"
# ENV{MOUNTPOINT}!="", ACTION=="add", RUN+="/lib/udev/storage.sh add $env{MOUNTPOINT}"
# ENV{MOUNTPOINT}!="", ACTION=="remove", RUN+="/lib/udev/storage.sh remove $env{MOUNTPOINT}"
# Note that the ENV{DEVNAME}!="/dev/mmcblk0p?" above is for the Raspberry PI's SD boot device.
# This doesn't solve the problem of disks that share the same label. I don't think this can be cleanly done with udev alone.
MOUNT_BASE='/media/'
MOUNT_USER=root
MOUNT_GROUP=plugdev
MOUNT_OPTIONS=rw,flush,user,umask=002,dmask=002,fmask=002 # Other options (breaks POSIX): noatime,nodiratime,nosuid,nodev
UNSAFE_CHARS='\0-\037\041-\057\072-\100\133-\140\173-\177'
case $1 in
mountpoint)
# Pick the mountpoint name according to partition or device name
dir="$(echo "$ID_FS_LABEL" | tr "$UNSAFE_CHARS" _ | sed -e 's/^_*//' -e 's/_*$//')"
if [ -z "$dir" ]; then
dir="${DEVNAME##*/}"
fi
if [ -n "$dir" ]; then
# Make available to rules
echo "$MOUNT_BASE$dir"
fi
;;
add)
mkdir -p "$2"
chown $MOUNT_USER:$MOUNT_GROUP "$2"
uid=$(id -u $MOUNT_USER)
gid=$(grep $MOUNT_GROUP /etc/group|cut -f3 -d:)
mount -t "$ID_FS_TYPE" -o "$MOUNT_OPTIONS,uid=${uid-0},gid=${gid-0}" $DEVNAME "$2"
;;
remove)
umount -l $2
rmdir $2
;;
esac
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment