How to Automatically Unmount an Inactive USB Drive in Linux

Leaving an external USB hard drive or flash drive permanently mounted to your Linux server can pose a security risk and unnecessary wear on the physical drive itself. However, if the drive is used for automated tasks like nightly backups, manually mounting and unmounting it every day is tedious. By using a Linux daemon called autofs, you can configure your server to automatically mount the USB drive the exact moment a script attempts to access it, and automatically unmount it after a period of inactivity.

How to Install and Configure autofs

The autofs utility runs silently in the background, monitoring specific mount points. When a user or script requests a file from that location, autofs mounts the drive dynamically.

  1. Log into your Linux server via SSH.
  2. Update your package list and install the utility: sudo apt update && sudo apt install autofs -y
  3. Once installed, we must edit the master configuration file to tell autofs where to monitor. Open it using nano: sudo nano /etc/auto.master
  4. Scroll to the bottom and add the following line. This tells autofs to manage the /mnt/usb directory and look for specific instructions in a secondary file called auto.usb, with a strict timeout of 60 seconds of inactivity: /mnt/usb /etc/auto.usb --timeout=60
  5. Save the file and exit (Press Ctrl+O, Enter, then Ctrl+X).

How to Map the Specific USB Drive

Now we must link the specific physical USB drive to that mount point using the drive’s unique UUID.

  1. Plug in your USB drive and run sudo blkid to find its UUID (e.g., UUID="1234-ABCD").
  2. Create the secondary map file we referenced earlier: sudo nano /etc/auto.usb
  3. Add the following line, replacing the UUID with your own, and defining the file system type (e.g., ext4, vfat, ntfs): backup_drive -fstype=ext4,rw :/dev/disk/by-uuid/1234-ABCD
  4. Save and exit the text editor.
  5. Restart the daemon to apply the changes: sudo systemctl restart autofs

How the Automation Works

Your USB drive is now managed by autofs. If you run the df -h command, the drive will not appear as mounted. However, the moment you attempt to list the contents of the directory (ls /mnt/usb/backup_drive) or a backup script attempts to write a file there, autofs will intercept the command, instantly mount the drive, and process the request.

Because we set --timeout=60 in the master file, the daemon will start a timer the moment the read/write operation finishes. If 60 seconds pass without any further activity on the drive, autofs will automatically unmount it, safely disconnecting it from the operating system until it is needed again.

Get the best tech tips delivered straight to your inbox.

Join thousands of readers mastering Apple, Google, Microsoft, and Linux.