In VirtualBox, expanding hard drive will gradually use up more and more space and user will end up with a big file that consists of mostly unused data, emptying trash is not enough, one must use special tools to shrink virtual hard drive. Assuming you use VirtualBox, check whether you use virtual disk image .vdi. According to manual, it is the native VirtualBox format and only this one supports the –compact option to this date.

Using zerofree, we can fill all free space on .vdi file with zeros, this will enable vboxmanage with –compact option to cut off empty bits and leave only .vdi file with real data.

First install zerofree if you have not done so already and change to single-user mode using init 1:

$ sudo apt-get install zerofree
$ sudo init 1

Then  unmount the partition, that you want to shrink, in my case it is /home = /dev/sda7, because all my non-system files are on it. Stop all other running services, otherwise you will get / busy statement on remount. Command zerofree -v /dev/sda7 wipes free space on selected partition with zeros in -v verbose mode.

To get out of the single-user mode in Ubuntu, you have to use shutdown -h now, otherwise it does not work.

# umount /dev/sda7
# service rsyslog stop
# mount -o remount,ro -t ext4 /dev/sda7 /
# zerofree -v /dev/sda7
# shutdown -h now

Use vboxmanage to compress .vdi

$ vboxmanage modifyhd "/home/VirtualBox VMs/Ubuntu.12.04/Ubuntu.12.04.vdi" compact