Skip to content

Instantly share code, notes, and snippets.

@jramapuram
Created August 26, 2025 16:20
Show Gist options
  • Save jramapuram/f962ab07ece81d83a3c91a250d1d8c63 to your computer and use it in GitHub Desktop.
Save jramapuram/f962ab07ece81d83a3c91a250d1d8c63 to your computer and use it in GitHub Desktop.
set -euo pipefail
# Detect the largest NTFS partition (usually C:)
WIN_NUM=$(lsblk -pno NAME,FSTYPE,SIZE "$DST" \
| awk '$2=="ntfs"{print $1,$3}' \
| sort -k2 -hr | head -1 \
| sed -E 's#.*/nvme[0-9]+n1p([0-9]+).*#\1#')
WIN_PART="${DST}p${WIN_NUM}"
echo "Detected Windows (NTFS) partition: $WIN_PART"
# Find the last partition by on-disk start sector (not by number)
LAST_NUM=$(parted -m "$DST" unit s print \
| awk -F: 'NR>=3 && $1 ~ /^[0-9]+$/ {print $1,$2}' \
| sort -k2 -n | tail -1 | awk '{print $1}')
LAST_PART="${DST}p${LAST_NUM}"
LAST_TYPE=$(lsblk -no PARTTYPE "$LAST_PART" | tr 'A-Z' 'a-z' || echo "")
# If last partition is WinRE, delete it so C: can grow
# WinRE type GUID: de94bba4-06d1-4d40-a16a-bfd50179d6ac
if [ "$LAST_NUM" != "$WIN_NUM" ] && [ "$LAST_TYPE" = "de94bba4-06d1-4d40-a16a-bfd50179d6ac" ]; then
echo "Deleting trailing Windows Recovery partition $LAST_PART to allow C: to expand..."
sgdisk -d "$LAST_NUM" "$DST"
partprobe "$DST"
udevadm settle
fi
# Re-evaluate last partition after potential deletion
LAST_NUM=$(parted -m "$DST" unit s print \
| awk -F: 'NR>=3 && $1 ~ /^[0-9]+$/ {print $1,$2}' \
| sort -k2 -n | tail -1 | awk '{print $1}')
if [ "$LAST_NUM" != "$WIN_NUM" ]; then
echo "C: (NTFS) is not the last partition and the last partition is not WinRE."
echo "Automatic expansion cannot proceed without moving partitions."
echo "Use gparted to move the blocking partition behind C:, or delete it if unneeded, then rerun the resize steps."
exit 2
fi
# Grow the C: partition to the end of the disk
parted -s "$DST" resizepart "$WIN_NUM" 100%
partprobe "$DST"
udevadm settle
# Expand the NTFS filesystem to fill the enlarged partition
# If Windows wasn't cleanly shut down, ntfsresize will refuse; in that case, boot Windows once and shut down cleanly.
ntfsresize -f "$WIN_PART"
echo "Expansion complete."
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment