Skip to content

Instantly share code, notes, and snippets.

@AndreVallestero
Last active June 30, 2021 19:26
Show Gist options
  • Save AndreVallestero/d0794b91e76653e51c109c5ee03fc834 to your computer and use it in GitHub Desktop.
Save AndreVallestero/d0794b91e76653e51c109c5ee03fc834 to your computer and use it in GitHub Desktop.
Guide for cloning drives to make a minimal image

It is recommended that you only have 2 partitions, boot and root, and that your boot partition is located before your root partition.

Use seperate live OS and follow steps in order.

For root partition where {a} is the partition name and {b} is the entire drive to clone

  • sudo mount /dev/{a} /mnt
  • sudo e4defrag /mnt
  • sudo fstrim /mnt may not work unless on a SSD
  • sudo umount /mnt
  • sudo e2fsck -f /dev/{a}
  • sudo resize2fs -M /dev/{a} note the block count and block size
  • fdisk -u -l /dev/{b} note the drive's sector size and your partition's start sector
  • sudo fdisk dev/{b} list the partitions using p and note the start sector, delete the partition, then create a new one
    • start sector is the same as before it was deleted
    • end sector is calculated using the following
    fs_size = block_count * block_size
    fs_sectors = fs_size/sector_size
    part_sectors = ((fs_sectors-1)/2048+1)*2048
    end_sector = start_sector + part_sectors - 1
    • do NOT remove the ext4 signature
  • sudo zerofree /dev/{a}

Then where {c} is the drive's block size, and {d} is the new end sector + 1 (use fdisk -u -l /dev/{b} if you forgot)

  • dd if=/dev/{b} bs={c} count={d} | pigz > image.iso.gz

If you have a really small root partition (less than 200MB) or you have an REALLY powerful CPU, use pigz -11 for better compression.

To flash the image on Linux, use one of the following where {x} is the device you would like to flash:

  • pigz -cd image.iso.gz | dd of=/dev/{x}
  • gunzip -c image.iso.gz | dd of=/dev/{x}

On windows, use Etcher or Rufus to flash.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment