script to backup entire drive and make it bootable

The script will:

  1. Auto-detect the USB device and UUID.

  2. Prompt you for confirmation after showing df -h.

  3. Run rsync, update the cloned /etc/fstab, bind-mount essential filesystems,

  4. Then chroot and auto-run grub-install and update-grub — all without further input.

  5. once you have run this script, run the efi installer script in another post.


#!/bin/bash

# Step 1: Detect USB disk
usb_devs=()
for dev in /sys/block/sd*; do
    devname=$(basename "$dev")
    [[ "$devname" =~ [0-9]$ ]] && continue
    if ls -l /dev/disk/by-path/ | grep -w "$devname" | grep -q usb; then
        usb_devs+=("/dev/$devname")
    fi
done

# Step 2: Verify only one USB drive is connected
if [ "${#usb_devs[@]}" -ne 1 ]; then
    echo "Error: Found ${#usb_devs[@]} USB drives. Please ensure only one external USB drive is connected."
    exit 1
fi

usb_device="${usb_devs[0]}"
usb_partition="${usb_device}1"
usb_uuid=$(blkid -s UUID -o value "$usb_partition")
user=$(logname)
usb_mount="/media/$user/$usb_uuid"

# Ensure the partition is actually mounted
if ! mountpoint -q "$usb_mount"; then
    echo "Error: Expected mount point $usb_mount not found. Aborting."
    exit 1
fi

echo "USB device: $usb_device"
echo "USB partition: $usb_partition"
echo "USB UUID: $usb_uuid"
echo ""
echo "Mounted filesystems:"
df -h | grep "^/dev"
echo ""
read -p "Proceed with this device? Type YES to continue: " confirm
[ "$confirm" != "YES" ] && echo "Aborted." && exit 1

# Step 3: Run backup
echo "Copying..."
rsync -avu / "$usb_mount/" \
  --exclude="media" --exclude="kcore" --progress \
  --exclude="ntfs" --exclude="proc/" --exclude="sys/" --exclude="google-chrome" --exclude="cache" --exclude=".cache"

# Step 4: Update fstab on backup
echo "Making the external drive bootable..."
cat <<EOF | tee "$usb_mount/etc/fstab"
UUID=$usb_uuid /               ext4    errors=remount-ro 0       1
UUID=4C51-A2B2  /boot/efi       vfat    umask=0077      0       1
EOF

# Step 5: Chroot and install GRUB
echo "Switching to external drive as if booting from it..."
mount --bind /dev "$usb_mount/dev"
mount --bind /proc "$usb_mount/proc"
mount --bind /sys "$usb_mount/sys"
chroot "$usb_mount" /bin/bash -c "grub-install $usb_device && update-grub"

echo "Backup and bootloader install complete."

Popular posts from this blog

Automatically Fix Song Metadata and Filenames on Linux with Beets

throttle traffic on apache

Enable Anydesk on Linux