I wanted to share a way how to keep your VirtualBox virtual hard disks compact, without the need of manually "zeroing" the free space in your VM and running

 VBoxManage modifyhd ... --compact



It only works if your virtual harddisks are stored on an SSD drive and if they are in VDI format. First you have to remove the hard disk from your virtual machine. DON'T DELETE the hard disk, only remove it. Then you attach it from the command line with the following command

VBoxManage storageattach "NameOfVM" --storagectl "SATA" --port 0 --device 0 --nonrotational on --discard on --medium "/path/to/harddisk.vdi" --type hdd

"Port 0" is the first SATA controller and "device 0" is the first hard disk of your VM. Change these values if necessary as well as "/path/to/harddisk.vdi". This command adds the discard="true" to your settings in the *.vbox file. When I tried to add this manually to the *.vbox file, it didn't work and this entry got deleted by VB on the next start.

If you mount your filesystems with the "discard" option, deleted sectors will be automatically trimmed and thus the vdi shrinks automatically too. Otherwise you have to run "fstrim" for each mounted filesystem manually or via a cronjob.