By Blueberry Coder on Dec 02, 2013
One of the nice things with Oracle VM VirtualBox is that you don't need to allocate all the disk space in advance. It is possible, say, to give a 60 Gb hard drive to a virtual machine but have an actual footprint much lower than that by creating the hard drive in dynamically allocated storage mode. Basically, this means the actual size for the hard drive will match the size of the files it contains. The footprint will grow over time, as you add files. Unfortunately, this is a one way process. The virtual hard drive will take more space on disk as it grows, but will not release the space if it shrinks. This can be a problem, for example, if you copied several Fusion Middleware installers on the VM and want to recuperate that space after installation.
I am currently playing with VMs a lot, and found a way to get the space back. This is a two step process. The first step is to fill the empty space with zeroes. There are utilities for that on Windows and OS X, but you can do it very easily on the command line on Oracle Enterprise Linux. Simply execute the following commands inside the virtual machine as root (or prefix with sudo):
Obviously, you should close all other programs before doing this, and ensure no background process will require disk space while dd is running.
Once this is done, shut down the VM and open a command line on the host machine. Go to the folder where VirtualBox is installed, and type something like this, substituting the correct path and file name for the virtual hard drive:
After a few minutes, you will get the wasted space back.
VirtualBox, by the way, has an extensive collection of command line utilities. You can even run a VM without opening the VirtualBox GUI using the VBoxHeadless command, for example. Also: did you know it is possible to start a VM in headless mode from the GUI? Simply press shift at the same time you click on the start button.