title: Shrink a vmdk Virtualbox disk image
body: <p>VirtualBox is able to compact (reduce the size) of <code>.vdi</code> images but it is not possible with <code>.vmdk</code> disk images. But we can compact <code>.vmdk</code> files if we:</p>
  
  <ol>
  <li>detach</li>
  <li>convert to <code>.vdi</code></li>
  <li>compact</li>
  <li>convert back to <code>.vmdk</code></li>
  <li>attach again to the original vitual machine</li>
  </ol>
  
  <p>So I tried to shrink my VirtualBox image with this script:</p>
  
  <pre><code>#/bin/bash
  
  VM_PATH=~/VirtualBox\ VMs
  cd "$VM_PATH"
  VM="$(ls ffnord-example_gc-gw0_* -d -1|head -n 1)"
  cd "$VM"
  VM_VDMK_NAME="$(ls *.vmdk -1|head -n 1)"
  VM_NAME="$VM_PATH/$VM/$VM_VDMK_NAME"
  
  echo reducing size of "$VM_NAME"
  ls -lah "$VM_NAME"
  set -x
  vboxmanage showvminfo "${VM}"
  vboxmanage storageattach "${VM}" --storagectl SATA --port 0 --device 0 --type hdd --medium none
  vboxmanage clonehd --format vdi "${VM_NAME}" /tmp/VM-disk.vdi
  vboxmanage closemedium disk "${VM_NAME}" --delete
  vboxmanage modifyhd /tmp/VM-disk.vdi --compact
  vboxmanage clonehd --format vmdk /tmp/VM-disk.vdi "${VM_NAME}"
  vboxmanage closemedium disk /tmp/VM-disk.vdi --delete
  vboxmanage storageattach "${VM}" --storagectl SATA --port 0 --device 0 --type hdd --medium 4/VMs/VM-disk1.vmdk
  </code></pre>
  
  <p>I adapted <a href="http://crysol.github.io/recipe/2013-10-15/virtualbox-compact-vmdk-images/" rel="noreferrer">this script from crysol</a> but it seems this is not working on Ubuntu? The first <code>vboxmanage storageattach</code> starts with an error right away:</p>
  
  <pre><code>VBoxManage: error: Could not find a controller named 'SATA'
  </code></pre>
  
  <p>If I try <code>"SATA Controller"</code> instead:</p>
  
  <pre><code>vboxmanage storageattach "${VM}" --storagectl "SATA Controller" --port 0 --device 0 --type hdd --medium none
  </code></pre>
  
  <p>I get this error:</p>
  
  <pre><code>VBoxManage: error: No storage device attached to device slot 0 on port 0 of controller 'SATA Controller'
  VBoxManage: error: Details: code VBOX_E_OBJECT_NOT_FOUND (0x80bb0001), component SessionMachine, interface IMachine, callee nsISupports
  VBoxManage: error: Context: "DetachDevice(Bstr(pszCtl).raw(), port, device)" at line 381 of file VBoxManageStorageController.cpp
  </code></pre>
  
  <p>If I comment out those <code>vboxmanage storageattach</code> lines, the script works fine, but the resulting VM is the same size as before and it doesn't boot anymore.</p>
  
  <p>This is the <a href="https://gist.github.com/rubo77/34ca2193355c3c73cd22" rel="noreferrer">output of <code>vboxmanage showvminfo "${VM}"</code></a></p>