1

I have a raw disk image I took using dd of a Ubuntu instance. The total disk size is 300 GB, but only 5.5 GB used.

Is there a way to resize the raw dd image down to 20 GB, keeping all of the 5.5 GB of data, and just truncating empty blocks?

Justin
  • 5,008
  • 19
  • 58
  • 82

3 Answers3

2

Just use virt-sparsify.

In its normal use, it writes a temporary file and then rewrites the original, with holes.

If you're short on disk space, it can even reduce the file in-place, without writing a temporary copy, with the -i option, though this may not free up all possible space.

Michael Hampton
  • 237,123
  • 42
  • 477
  • 940
1

On reasonably recent versions of dd, you can use conv=sparse to create the image file as sparse right from the start.

One thing to note is that just because a disk block is "unused", doesn't mean it's actually full of zeroes, if the block was occupied by a file that has since been deleted. There is a tool called zerofree which can take an (unmounted) filesystem and fill all the unused blocks with zeroes, which makes the subsequent sparsification work better.

womble
  • 95,029
  • 29
  • 173
  • 228
  • Can I run `zerofree` on a dd created file directly? – Justin Aug 18 '15 at 03:30
  • Only if the image is of a partition. For a whole-disk image, you can read the partition table and create partitions on which you can run `zerofree` with a combination of `losetup` and `kpartx`. – womble Aug 18 '15 at 03:34
0

If you make it a sparse file, the file metadata will still be 300 GB, but the actual space used will be closer to 5.5. Such as with GNU cp --sparse=always

See also: How do I convert a Linux disk image into a sparse file?

If you want to reduce the files logical size as well, you need to reduce the file system, LVM, and whatever else you have depending on the disk size.

It may be simpler to mount the large image, create a new image of the desired size, and copy files to it.

John Mahowald
  • 30,009
  • 1
  • 17
  • 32