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.


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

diskutil secureErase freespace 0 /


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

sdelete.exe -c C:


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

One thought on “Compacting VirtualBox disks

  1. This trick also applies to physical disk. Fill the empty clusters with zeroes improves the results in the image compression level. I use it often to create backup. I use it on linux, but I think it also applies to other os.


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s