Clone disks the lean way

Alex Kaouris
2 min readDec 8, 2021

I’m sure you have more then once needed to clone a disk so as to keep an image backup of your OS or use it to clone other instances of the same setup. I’ve done that more then I can remember though one annoying issue that I was frequently faced with was where to store all those disk images. Even if you have TBs of available storage that is very easily depleted when working with large image files, until I found out about the sparse files.

So one can use dd to backup the whole disk image and do that without keeping the blocks marked with zero. So, below are the steps that one would follow in that case:

Backup the disk as a disk image file:

Say you have disk /dev/sdx that you need to backup as an image file named mydisk.img and later burn it on another disk named /dev/sdy. First you need to fill the partitions of the /dev/sdx with zero. Example:

At a mounted partition run:

dd if=/dev/zero of=tempzero.txt

This will zero the free space of the partition. As soon as dd is completed you then delete this file:

rm tempzero.txt

Repeat for each partition in case you have multiple ones. Shutdown the OS that is using the disk /dev/sdx, as the partitions of the disks must not be mounted for the next step.

Record the disk as an image file using sparse mode:

dd if=/dev/sdx of=mydisk.img bs=512 conv=sparse status=progress

It is important to keep the bs=512 so as the dd to be able to scan all the zeroed parts of the disk.

So by now you should have your disk backup as a sparse file. You can check the actual size of the image with:

du -sh mydisk.img

Restore the image file to a disk:

To burn the image file to a disk, you do it as usually:

dd if=mydisk.img of=/dev/sdy bs=1M status=progress

In this case you can use your preferred block size (bs=1M or other).

Note that in case you need to backup your image file to a backup media, and I hope you do that as a great systems admin you are :) you need to use tools that support sparse files. I prefer rsync with the --sparse flag.

P.S. you may be interested also to use virt-sparsify for VM disk images. It has given me the same good results.

--

--

Alex Kaouris

Seasoned Systems Engineer that enjoys grappling with open source technologies to find simple solutions to seamingly difficult problems.