Already answered here dd-on-entire-disk-but-do-not-want-empty-portion
Assuming you want to save /dev/sdXN
to /tgtfs/image.raw
and you are root:
mkdir /srcfs && mount /dev/sdXN /srcfs
Use zerofill or just:
dd if=/dev/zero of=/srcfs/tmpzero.txt
To fill unused blocks with zero (wait for it to fill the file system completely then
rm /srcfs/tmpzero.txt
Take the image with dd
and use conv=sparse
to punch zeros on-the-fly:
dd conv=sparse if=/dev/sdxn of=/tgtfs/image.raw
If you want to use compression you don't need to punch the zeros with dd
as zero blocks are highly compressible:
dd if=/dev/sdxn | gz -c | dd of=/tgtfs/image.raw
PS: You should note that this is not a good idea on a flash memory based storage media (i.e. your source file system be SSD).