Páginas

Monday, January 2, 2017

Backing up entire disks and making .img files smaller

As part of migrating to a new laptop and backing up an entire disk partition, here I document what I have done.

Creating full disk images

Work from a Live USB with Fedora 25 or any other modern distro, so that the partitions that will be backed up are not in use.
Use the Disks utility to create a disk image of some partition, e.g., the original /home.

This will create a .img file as big as the partition size, independent of how much data is actually stored. Next, we shrink the image to a minimal size to fit the data it contains, potentially saving some backup space.

Shrink disk image to its minimal size

If all you have is a single partition image, as created in the step above, we can use a loop device and the resize2fs utility to make the image smaller.

First, we'll find an available loop device with:

sudo losetup -f

Note down the name of the loop device, e.g., /dev/loop1, and use it in the next steps.

Mount the image:

sudo losetup /dev/loop1 'Disk Image of ... .img'

And resize it to its minimum size:

sudo resize2fs -Mp /dev/loop1

The -M flag resizes the image to the minimum size; while -p prints progress information.
Be patient, resize2fs may take some time depending on the partition size, disk speed, etc.

Note: if you get an error from the command above, it might be needed to run this before running resize2fs again (the error message will tell):

sudo e2fsck -f /dev/loop1

When resize2fs finishes, unload the loop device:

sudo losetup -d /dev/loop1

Finally, run resize2fs on the .img file to resize it:

resize2fs -Mp 'Disk Image of ... .img'

This should be relatively fast.
We're done! Check the new image size.

1 comment:

Rodolfo said...

Today I ran into a new problem: the disk I wanted to make an image of was bigger than any other place where I could write the backup .img file.
And to add to that, the partitions were encrypted with LUKS.

The solution I went with was to first resize/shrink the original partition, roughly following the steps in https://unix.stackexchange.com/a/339843, and then proceed with the original steps in this blog post. Note that there's an inherent danger when shrinking the original partition!