From 81a3318a5f09ea325b71a54c0202a8fce80c6ee9 Mon Sep 17 00:00:00 2001 From: grabowski Date: Mon, 27 Oct 2025 15:11:17 +0700 Subject: [PATCH] Add systemd-based USB auto-mount setup script MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Created setup_usb_automount.sh to solve fstab auto-mount issues with modern systemd-based Raspberry Pi OS. Features: - Creates systemd .mount and .automount units - Extracts UUIDs from existing /etc/fstab automatically - Allows manual UUID entry if not found - Auto-mounts when USB drives are accessed (on-demand) - Works even if USB drives are plugged in after boot - Proper user permissions (uid/gid) - Easy enable/disable via systemctl This solves the issue where fstab entries don't auto-mount because USB drives aren't present at boot time or systemd has different mounting priorities. Usage: sudo ./setup_usb_automount.sh 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude --- setup_usb_automount.sh | 173 +++++++++++++++++++++++++++++++++++++++++ 1 file changed, 173 insertions(+) create mode 100644 setup_usb_automount.sh diff --git a/setup_usb_automount.sh b/setup_usb_automount.sh new file mode 100644 index 0000000..e07f86e --- /dev/null +++ b/setup_usb_automount.sh @@ -0,0 +1,173 @@ +#!/bin/bash +# +# USB Auto-mount Setup using systemd +# This creates systemd mount units that auto-mount when USB drives are inserted +# + +set -e + +# Colors for output +RED='\033[0;31m' +GREEN='\033[0;32m' +YELLOW='\033[1;33m' +NC='\033[0m' # No Color + +echo "==========================================" +echo "USB Auto-mount Setup (systemd)" +echo "==========================================" +echo "" + +# Check if running as root +if [ "$EUID" -ne 0 ]; then + echo -e "${RED}This script needs sudo privileges${NC}" + echo "Please run with: sudo ./setup_usb_automount.sh" + exit 1 +fi + +# Get the real user (not root when using sudo) +REAL_USER=${SUDO_USER:-$USER} +REAL_UID=$(id -u $REAL_USER) +REAL_GID=$(id -g $REAL_USER) + +echo "Setting up auto-mount for user: $REAL_USER (UID:$REAL_UID, GID:$REAL_GID)" +echo "" + +# Create mount points +echo "Creating mount points..." +mkdir -p /media/usb0 /media/usb1 +chown $REAL_UID:$REAL_GID /media/usb0 /media/usb1 +echo -e "${GREEN}✓ Mount points created${NC}" +echo "" + +# Detect USB devices and get UUIDs +echo "Detecting USB devices..." +lsblk -f | grep -E "sd[a-z][0-9]|vfat|exfat|ntfs" +echo "" + +# Function to create systemd mount unit +create_mount_unit() { + local uuid=$1 + local mount_point=$2 + local unit_name=$(systemd-escape -p --suffix=mount "$mount_point") + + echo "Creating systemd mount unit: $unit_name" + + cat > "/etc/systemd/system/$unit_name" < "/etc/systemd/system/$automount_unit" <