A reliable Bash script for secure and efficient synchronization of a local directory to a USB flash drive using rsync.
Unlike simple copy commands, this script acts defensively: it validates hardware states, calculates data payloads, checks boundaries, and prevents data loss before a single byte is written.
- 🔒 Hardware Mount Validation: Ensures the specified USB flash drive is genuinely mounted at the target path before initiating execution to prevent writing to the root filesystem.
- 📊 Pre-flight Storage Calculation: Dynamically measures the source directory size using
duand compares it against the exact available space on the flash drive viadf. If space is insufficient, it aborts gracefully. - 🔄 Intelligent Synchronization (
rsync): Utilizesrsyncmirroring (--delete) to keep your backup atomic and clean, ensuring files deleted from the source are also pruned from the destination. - 📈 Global Progress Tracking: Employs
--info=progress2to provide a clean, modern, single-line global transfer progress bar instead of cluttering the terminal output with thousands of individual file names. - 🛡️ Defensive Error Handling: Implements precise exit status trapping (
set -epaired with selectiveset +e) to intercept and reportrsyncruntime anomalies safely.
The script relies on standard Linux utilities. Before running, ensure you have the following installed (standard on almost all distributions):
bash(interpreted shell, version 4.0+)rsync(fast, versatile, remote and local file-copying tool)numfmt(utility to convert numbers to/from human-readable formats, part of GNU coreutils)coreutils(provides nativedf,du, andmkdircommands)
git clone [https://github.com/your-username/your-repo-name.git](https://github.com/your-username/your-repo-name.git)
cd your-repo-nameOpen backup-flash.sh in your favorite text editor (e.g., nano or sublime) and locate the Configuration block. Modify the values to match your specific environment:
# ===== Configuration =====
SRC="$HOME/Dir/" # The local folder you want to back up
FLASH_LABEL="BACKUP_USB" # The volume label/name of your USB drive
BACKUP_DIR="DIR-SYNC" # The target folder name inside the USB drive
# =========================