How to create an .IMG image of a disc (sd card) without including free space?

Necktwi picture Necktwi · Oct 14, 2013 · Viewed 72.3k times · Source

In Linux, we can do

dd if=/dev/sdb of=bckup.img

but if the disk is of 32GB with only 4GB used, the 32GB image file is waste of space-time. Is there any way or tool to create images with only valid data?

Answer

mvp picture mvp · Oct 14, 2013

Pretty good and simple way to deal with this is simply pipe it via gzip, something like this:

# dd if=/dev/sdb | gzip > backup.img.gz

This way your image will be compressed and most likely unused space will be squeezed to almost nothing.

You would use this to restore such image back:

# cat backup.img.gz | gunzip | dd of=/dev/sdb

One note: if you had a lot of files which were recently deleted, image size may be still large (deleting file does not necessarily zeroes underlying sectors). You can wipe free space by creating and immediately deleting large file containing zeros:

# cd /media/flashdrive
# dd if=/dev/zero of=bigfile bs=1M     # let it run and quit by disk full error
# rm bigfile