Wednesday, February 6, 2008

Cloning disk images with dd and cp, keeping them sparse

Today I'm writing a method (that I have not yet tested enough!) to make a copy of a partition using only the standard dd and cp commands (gnu version, I tested it on suse10.2 and xubuntu). It is recommended to copy unmounted partitions only, as a mounted partition could change when it is read!

1.$ mount /dev/sda1 /mnt/sda1 # mount the partition, e.g. in /mnt/sda1
2.$ cd /mnt/sda1
3.$ dd if=/dev/zero of=fill.txt # to fill the free disk space
4.$ rm fill.txt
5.$ umount /dev/sda1 # unmount the partition to be cloned
6.$ cd ~/disk_images # choose whichever directory you want
7.$ cp --copy-contents --sparse=always /dev/sda1 sda1.img
8.$ ls -lsh # will show you the real size of the cloned partition

Well I know it is not clear enough to whom doesn't know this topic, anyway you can find a lot of information and software on this topic, for instance this article on freshmeat.
The matter is, this method copies a partition efficiently, allocating space for the non zero sectors only, so it should be as efficient as most clone softwares, but relies only on standard linux commands.
Hope that helps, and if not, I hope I'll receive some comment!