Compacting VirtualBox disks

For my development tasks I often use VirtualBox, mostly for testing purposes. Sadly though, installing multiple operating systems consumes quite a lot of disk space, so I need some way to keep the virtual disks small.

Because you can use auto expanding virtual disks you might think they will automatically shrink if you reduce the amount of content in there, but this is not true: if you have a virtual disk of say 40GB and 30GB in use, your VDI file size will be about 30GB, but if you delete 20GB of data from within your virtual disk the VDI file size will remain 30GB.

That space can be reclaimed though by using a command line tool called vboxmanage which provides a command called modifyhd which in turn has a –compact option.

In other words you can execute something like

vboxmanage modifyhd your/virtual/hard/disk/file.vdi --compact

and shrink your VDI file to its real content size… if you managed to wipe your virtual disk free space with zeroes!

Do not underestimate the last statement: the vboxmanage tool will eliminate from your VDI file empty space only, but usually when you delete a file the space it was occupying is not emptied, just unlinked!

Luckily for us there are tools around to help us on this task, which has to be executed from within the virtualized machine (aka the guest machine). These tools though depend on the virtual OS you are running.

Mac OSX

Open a terminal window and run the following command, then wait and ignore the warnings you get.

diskutil secureErase freespace 0 /

Windows

Defrag your disk, download SDelete from the Windows Technet web site and run it with the -c option.

sdelete.exe -c C:

Linux

Run this command and wait for it’s completion. Note though this will expand your virtual disk to it’s maximum capacity to allow you to shrink it.

cat /dev/zero > /tmp/junk & rm /tmp/junk