Automatically Mounting USB Disks on Ubuntu

🔖 snippets ⏲️ 1 minute to read

This snippet is for a "watchdog" batch script run as a systemd service, which automatically mounts disks if they're not mounted.

This is useful for USB disks which should always be connected, but sometimes aren't (e.g. in the event of power loss, where the drive has to be manually turned back on). Here's the script, which is stored as /opt/ext-mount.sh:

#!/bin/bash
while true
do
        for mnt in /mnt/*/; do
                if findmnt --mountpoint $mnt > /dev/null; then
                        continue
                fi
                echo "$mnt does not appear to be mounted, mounting..."
                mount --target $mnt
        done
        sleep 60
done

It loops all mount points under /mnt, and if it detects they're not available, tries to mount them. There may be more elegant ways to do this, but the above script is fairly simple.

Here are the corresponding /etc/fstab entries, note that they are set to noauto so they are not mounted at boot, and user so that a regular user account can mount them:

/dev/disk/by-uuid/e4cd0161-b8f6-4b3c-98f5-aba6f452eb25 /mnt/ext1 auto noauto,user
/dev/disk/by-uuid/86a24bca-ac32-4d8c-a7f8-af893dad5fac /mnt/ext2 auto noauto,user
/dev/disk/by-uuid/5d72f223-2c96-4a39-a81c-d9c4970f033b /mnt/ext3 auto noauto,user

To set up the systemd service, define /etc/systemd/system/ext-mount.service:

[Unit]
Description=ext-mount
After=network.target
StartLimitIntervalSec=0

[Service]
Type=simple
Restart=always
RestartSec=1
User=media
WorkingDirectory=/opt
ExecStart=/usr/bin/sh ext-mount.sh

[Install]
WantedBy=multi-user.target

Then to enable it:

systemctl enable ext-mount.service

To start it:

systemctl start ext-mount.service

To check its status:

systemctl status ext-mount.service

And to check the logs:

journalctl -u ext-mount

🏷️ disks script mount usb systemd mounted mounting ubuntu snippet watchdog batch mounts connect aren't power

⬅️ Previous post: Raspberry Pi Pico HTTP Admin Dashboard

➡️ Next post: Remembering USB Devices in VMware ESXi

🎲 Random post: 10 Year Anniversary of Estranged

Comments

Please click here to load comments.