script to create an EFI partition on a target bootdrive if none exists

After rsyncing your OS to the external drive, run this to create a boot partition.
You MUST copy the OS first.

#!/bin/bash

# Ensure script is run as root
if [ "$(id -u)" -ne 0 ]; then
  echo "Please run this script as root (e.g. via sudo)."
  exit 1
fi

# Load USB device detection
source /scripts/find_usb.sh || {
  echo "Failed to load /scripts/find_usb.sh"
  exit 1
}

mountpoint="/media/$(logname)/$usb_uuid"
efi_partition="${usb_disk}2"

echo "This will FORMAT and INSTALL EFI SYSTEM PARTITION on $efi_partition"
echo
df -h | grep "$usb_disk" || echo "Warning: device not mounted yet."
echo

read -rp "Continue with formatting and EFI install on $efi_partition? (y/n): " confirm
if [[ "$confirm" != "y" ]]; then
  echo "Aborted."
  exit 1
fi

# Create EFI partition if it doesn't exist
if ! lsblk "$efi_partition" &>/dev/null; then
  echo "Creating EFI partition on $efi_partition..."
  parted "$usb_disk" mkpart primary fat32 100MiB 300MiB
  parted "$usb_disk" set 2 esp on
  sleep 1
fi

# Format as FAT32
mkfs.vfat -F32 "$efi_partition" || {
  echo "Failed to format $efi_partition"
  exit 1
}

# Mount EFI and copy bootloader files
mkdir -p /mnt/efi
mount "$efi_partition" /mnt/efi || {
  echo "Failed to mount $efi_partition"
  exit 1
}

echo "Installing EFI bootloader to $efi_partition..."
mkdir -p "$mountpoint"/boot/efi
mount --bind /dev "$mountpoint/dev"
mount --bind /proc "$mountpoint/proc"
mount --bind /sys "$mountpoint/sys"
mount "$efi_partition" "$mountpoint/boot/efi"

chroot "$mountpoint" grub-install --target=x86_64-efi --efi-directory=/boot/efi --removable --recheck
chroot "$mountpoint" update-grub

# Cleanup
umount "$mountpoint/boot/efi"
umount "$mountpoint/dev"
umount "$mountpoint/proc"
umount "$mountpoint/sys"
umount /mnt/efi

echo "EFI setup complete."

Popular posts from this blog

Automatically Fix Song Metadata and Filenames on Linux with Beets

throttle traffic on apache

Enable Anydesk on Linux