udev rules 99-usb-mount-rules
# Warning this mounts only the first partition to the defined place, assuming first partition is 1
KERNEL=="sd[a-z]*1", SUBSYSTEMS=="usb", ACTION=="add", RUN+="/bin/systemctl start automount@%k.service"
KERNEL=="sd[a-z]*1", SUBSYSTEMS=="usb", ACTION=="remove", RUN+="/bin/systemctl stop automount@%k.service"
Add systemd service: automount@.service
[Unit]
Description=Automount usb drive to %i
[Service]
Type=oneshot
RemainAfterExit=true
Environment="MOUNTPOINT=/media/user_data/EXTERNAL"
ExecStart=/usr/bin/mount-usb-drive.sh add %i
ExecStop=/usr/bin/mount-usb-drive.sh remove %i
Add script to filesystem that actually mounts the usb drive:
#!/bin/bash
# First parameter indicates to add or remove drive.
# last parameter indicates the device name.
WATCHDIR="/tmp/swuwatchdir"
mkdir -p ${WATCHDIR}
usage()
{
echo "Usage: $0 {add|remove} device_name (e.g. sdb1)"
exit 1
}
function do_mount()
{
check_mount_state
# Get formatting of the drive. TYPE
# "blkid -o udev" option does not work for busybox version of blkid.
eval $(/sbin/blkid ${DEVICE} | tr " " "\n" | tail -n 1)
echo "Mounting ${DEVICE} of type ${TYPE} to ${MOUNTPOINT}"
/bin/mkdir -p ${MOUNTPOINT}
# Global mount options
OPTS="rw,relatime,sync"
# File system type specific mount options
if [[ ${TYPE} == "vfat" ]]; then
OPTS+=",users,gid=100,umask=000,shortname=mixed,utf8=1,flush"
fi
if ! /bin/mount -o ${OPTS} ${DEVICE} ${MOUNTPOINT}; then
echo "Error mounting ${DEVICE} (status = $?)"
/bin/rmdir ${MOUNTPOINT}
exit 1
fi
# Place dummy file in MOUNTPOINT/../mountWatch to not
# have to watch the entire user directory.
touch ${WATCHDIR}/asdf
echo "**** Mounted ${DEVICE} at ${MOUNTPOINT} ****"
}
function do_unmount()
{
if [[ ! -d ${MOUNTPOINT} ]]; then
echo "Warning: ${DEVICE} is not mounted"
else
/bin/umount -l ${DEVICE}
echo "**** Unmounted ${DEVICE}"
fi
rm ${WATCHDIR}/asdf
/bin/rmdir ${MOUNTPOINT}
}
function check_mount_state() {
# See if this drive is already mounted, and if so where
MOUNTED_TO=$(/bin/mount | /bin/grep ${DEVICE} | /usr/bin/awk '{ print $3 }')
if [[ -n ${MOUNTED_TO} ]]; then
echo "Warning: ${DEVICE} is already mounted at ${MOUNTED_TO}"
echo "We only expect one USB drive to be inserted at a time."
exit 1
fi
}
function main() {
if [[ $# -ne 2 ]]; then
usage
fi
ACTION=$1
DEVBASE=$2
DEVICE="/dev/${DEVBASE}"
# Var MOUNTPOINT should be set by the systemd script. Check it.
if [[ -z ${MOUNTPOINT} ]]; then
echo "MOUNTPOINT is not set by systemd script."
exit 1
fi
case "${ACTION}" in
add)
do_mount
;;
remove)
do_unmount
;;
*)
usage
;;
esac
}
main $@
Based on: https://serverfault.com/questions/766506/automount-usb-drives-with-systemd