Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
How to automatically mount/unmount an external USB hard drive
# File: /etc/udev/rules.d/85-external-drive-rule.rules
# Rules for auto-mounting/unmounting USB drives
ACTION=="add", ENV{ID_MODEL}=="USB_to_ATA_ATAPI_bridge", ENV{ID_VENDOR_ID}=="152d", ENV{ID_MODEL_ID}=="2338", RUN+="/usr/local/bin/"
ACTION=="remove", ENV{ID_MODEL}=="USB_to_ATA_ATAPI_bridge", ENV{ID_VENDOR_ID}=="152d", ENV{ID_MODEL_ID}=="2338", RUN+="/usr/local/bin/"
# Notes:
# To detect your own drive's ID_MODEL, ID_MODEL_ID, and ID_VENDOR_ID, run "udevadm monitor --environment --udev" before plugging/unplugging the drive
# To force udev to reload these rules (without reboot), run "udevadm control --reload-rules" and "udevadm trigger"
# To change udev's logging level (written to /var/log/syslog), you can run "udevadm control --log-priority=info" (or debug), or configure it via /etc/udev/udev.conf
# File: /usr/local/bin/
# Wait a few seconds for the drive to spin up after connecting
sleep 5
# Use the rules in /etc/fstab to automatically mount the drive
/bin/mount -a
# Tell the drive to spin down after 10 minutes
if [ -e /dev/sda ]; then
/sbin/hdparm -K1 -S120 /dev/sda
if [ -e /dev/sdb ]; then
/sbin/hdparm -K1 -S120 /dev/sdb
# File: /etc/fstab
# OS partitions (don't mess with 'em):
proc /proc proc defaults 0 0
/dev/mmcblk0p1 /boot vfat defaults 0 2
/dev/mmcblk0p2 / ext4 defaults,noatime 0 1
# At boot-time, automatically mount your external HDD, if detected
# To find the UUID, run "blkid"
UUID=<partition-uuid> /mnt/<path> ntfs-3g defaults,auto,noatime,nodiratime,noexec 0 0
# File: /usr/local/bin/
# The path you use could be the partition in /dev or could be the mount-point (something under /mnt, /media)
/bin/umount /mnt/<path>
A 3TB internal SATA drive is connected to my Raspberry Pi 2 Model B via a USB-to-SATA adapter.
I am using the RPi to run kodi; all the movies, videos, and TV shows are contained in the hard-drive.
My goals for drive-management are:
* To automatically detect and mount the drive at boot-time (if detected) => use /etc/fstab
* To automatically detect and mount the drive after boot-time (whenever hot-plugged) => write custom /etc/udev/rules.d/*.rules
* To automatically unmount the drive when it is unplugged/powered-off => write custom /etc/udev/rules.d/*.rules
* To spin down the hard-drive after a period of inactivity => piggy-back off the udev rules
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.