I had setup Virtual Box VM that could boot the same Linux root partition that was used for dual booting Linux (see the last post ). However after a few kernel upgrades the manual process to create the boot image needs to be repeated. Forget to do that and the VM no longer boots.

The process was taken from here: https://www.lifehacker.com.au/2013/05/how-to-dual-boot-and-virtualise-the-same-partition-on-your-computer/

The above needed a few customizeations. To save time a basic script to automate the above can be made.

  • It assumes the windows parition is mounted to /media/sf_windows_c/.
  • To keep the filename unique it creates a new image file using the date in the filename.
  • The parition table exposed by virtual box differs from the real parition table. For that reason the grub.cfg is edited to replace gpt5 with gpt4.
  • The default boot partiton is changed to 0, and the windows dual boot option is removed using a perl script.
BOOT_VOLUME=boot_$(date +%Y%m%d)
GRUB_CONF=/tmp/${BOOT_VOLUME}/boot/grub/grub.cfg

# Delete old version
rm -f /tmp/${BOOT_VOLUME}.iso
rm -rf /tmp/${BOOT_VOLUME}/

# Create the boot disk filesystem
mkdir -p /tmp/${BOOT_VOLUME}/boot/grub
cp -prf /usr/lib/grub/x86_64-efi /tmp/${BOOT_VOLUME}/boot/grub/
cp -prf /${BOOT_VOLUME}/efi /tmp/${BOOT_VOLUME}/
cp /boot/grub/grub.cfg /tmp/${BOOT_VOLUME}/boot/grub/

# Fix grub.conf
perl -pi remove-win.pl ${GRUB_CONF}
perl -pi -e 's/set default=.*/set default="0"/' ${GRUB_CONF}
perl -pi -e "s/hd0,gpt5/hd0,gpt4/g" ${GRUB_CONF}
perl -pi -e "s/ahci0,gpt5/ahci0,gpt4/g" ${GRUB_CONF}

# Create the disk image
grub-mkrescue -o /tmp/${BOOT_VOLUME}.iso /tmp/${BOOT_VOLUME}
cp /tmp/${BOOT_VOLUME}.iso /media/sf_windows_c/Users/Xxxx/VirtualBox\ VMs/Ubuntu/

The remove-win.pl script is here:

if (m@^menuentry 'Windows@) {
   $_ = "";
   $delete = 1;
}
if ($delete) {
   if (m@^}@) {
      $delete = undef;
   }
   $_ = "";
}

I suspect there is better way to do all this, but the VM is booting again so it will have to do.