Shrinking VirtualBox VDI's

This is nothing new, but I'm adding this here for myself, so I can find it again. Once in a while, dynamically allocated VDI's in VirtualBox will grow a lot more than what the guest OS reports as being used. When this happen, you can recover some space on the host system, doing the following.

First, in the guest OS, you can do one of the following:

mount -o remount,ro /dev/sda1
zerofree -v /dev/sda1

However, I could not get that to work, for some reason, it just said that it couldn't open the device. So, the second thing to do, which is what I do, is

sudo dd if=/dev/zero of=/bigemptyfile bs=4096k
sudo rm -rf /bigemptyfile
 
These commands will allow the VirtualBox command to recognize the zero-filled blocks that should be recovered:
VBoxManage modifyhd ~/VirtualBox/Linux/linux.vdi --compact

The commands varies slightly depending on the host OS, the above is on my Mac.