Skip to content

Instantly share code, notes, and snippets.

@andrewodri
Created August 7, 2019 02:18
Show Gist options
  • Save andrewodri/775bbf907edd0bb1e4bd014b24ae7bba to your computer and use it in GitHub Desktop.
Save andrewodri/775bbf907edd0bb1e4bd014b24ae7bba to your computer and use it in GitHub Desktop.
Resize partition within disk image file
#!/bin/bash
DATA_SIZE=$(du -s \
--exclude="*_[A-Z][A-Z].*" \
--exclude="*_[A-Z][A-Z]_*" \
--exclude="*_[A-Z][A-Z][A-Z].*" \
--exclude="*_[A-Z][A-Z][A-Z]_*" \
/data/ | cut -f1)
#########################################################################
# This is about the simplest way to resize a partition:
# 1. Append the required space to the disk image
# 2. Resize partition "2" to use the appended space
# 3. Expose the partitions as devices (synchronously, so that we don't encounter race conditions)
# 4. Modify the super block of the resized partition to match the new size
#########################################################################
truncate -s "+$(echo "(${DATA_SIZE} * 1024) + (1024 * 1024)" | bc)" "/tmp/raspbian.img"
echo ",+" | sfdisk -N 2 "/tmp/raspbian.img"
kpartx -a -s -v "/tmp/raspbian.img"
resize2fs -f /dev/mapper/loop*p2
BOOT_PARTITION=$(basename /dev/mapper/loop*p1)
DATA_PARTITION=$(basename /dev/mapper/loop*p2)
mkdir -p "/mnt/${BOOT_PARTITION}" "/mnt/${DATA_PARTITION}"
mount "/dev/mapper/${BOOT_PARTITION}" "/mnt/${BOOT_PARTITION}"
mount "/dev/mapper/${DATA_PARTITION}" "/mnt/${DATA_PARTITION}"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment