Shrink VirtualBox disk image

  • prerequisite: the virtual disk image is of type "dynamically expanding"
  • delete and install in the guest as much as you want
  • defrag your virtual disk, if necessary (Windows guests)
  • with the guest running, fill the free space on your virtual disk with zeros.

    • For Windows guests, use sdelete:

      sdelete -c c:
      
    • For Linux and BSD guests:

      cat /dev/zero > zero.fill;sync;sleep 1;sync;rm -f zero.fill
      
  • finally, with the guest shut down, issue the following command in your host system:

    VBoxManage modifyvdi virtualdiskname.vdi compact
    

YMMV, but I managed to save 2 GB in this way for a Windows XP guest.

Update: in VirtualBox 3.* and later, use the following command:

VBoxManage modifyhd --compact virtualdiskname.vdi

Furthermore, in more recent versions of sdelete, the command-line options 'c' and 'z' has been exchanged. To zero a disk, you now have to use

sdelete -z c: