Skip to content

Instantly share code, notes, and snippets.

@helamonster
Created June 12, 2025 05:49
Show Gist options
  • Save helamonster/4e741465bf2ad03c12dd4fe4853d6389 to your computer and use it in GitHub Desktop.
Save helamonster/4e741465bf2ad03c12dd4fe4853d6389 to your computer and use it in GitHub Desktop.
#!/usr/bin/env bash
#
# Example script to clone a disk to a new larger disk so that it will boot properly
#
# Dependencies:
# dd, sgdisk, partprobe, partclone, parted, ntfsresize
#
# Assumptions:
# The source disk is is a Windows boot disk partitioned with GPT and the last
# partition contains the OS filesystem (e.g. C:) formatted with NTFS
# Define source and destination device names (no /dev/ prefix)
DISK_SRC="sda"
DISK_DST="sdb"
# Clone MBR + GPT headers + partition table (first 2048 sectors as a safe approximation)
dd if=/dev/$DISK_SRC of=/dev/$DISK_DST bs=512 count=2048
# Use sgdisk to backup and restore the GPT layout
sgdisk -b /tmp/${DISK_SRC}.gpt /dev/$DISK_SRC
sgdisk -l /tmp/${DISK_SRC}.gpt /dev/$DISK_DST
# Re-read partition table on the destination disk
partprobe /dev/$DISK_DST
sleep 2
# Clone each partition using partclone
for PART in $(lsblk -ln -o NAME /dev/$DISK_SRC | grep -E "^${DISK_SRC}[0-9]+$"); do
SRC_PART="/dev/$PART"
SUFFIX="${PART#$DISK_SRC}"
DST_PART="/dev/${DISK_DST}${SUFFIX}"
echo "Cloning $SRC_PART to $DST_PART"
partclone -s "$SRC_PART" -o "$DST_PART"
done
# If you want to resize the last partition to fill the disk ...
# Resize the partition
parted /dev/${DISK_DST} resizepart ${PART} 100%
# Resize the filesystem to use all available partition space
ntfsresize --expand /dev/${DISK_DST}${PART}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment