Reboot To Windows From Linux With A Simple Script

I dual-boot Linux (Ubuntu) and Windows on my Desktop computer. Primarily, I use the Linux partition, and occasionally like to switch to Windows for other work.

Thus, I would like the following setup for my desktop:

  • When booting from power off, boot straight to Linux without interruption.

  • Be able to boot directly to Windows from Linux without BIOS access and without changing defaults.

The Solution

First, edit the file /etc/default/grub to ensure the following line is present: GRUB_DEFAULT=saved.

Then, update the grub config with your changes using the command update-grub.

Finally, run the following Python script as root to boot into Windows. Subsequent boots return you to Linux.

"""Reboot to windows."""
import re
import subprocess

if __name__=="__main__":
    ## Find Windows boot menu entry in the grub config.
    with open("/boot/grub/grub.cfg", "r") as open_file:
        grub_cfg = open_file.read()
    query = r"^menuentry '(.*?)'"
    flags = re.MULTILINE
    items = re.findall(query, grub_cfg, flags)
    for item in items:
        if "windows" in item.lower():
            boot_menu_entry = item
            break
    ###

    ## Set the reboot OS to Windows, and reboot if successful.
    grub_result = subprocess.run(
            ["grub-reboot", boot_menu_entry],
            capture_output=True)
    grub_error_result = grub_result.stderr.decode('utf-8')
    if grub_error_result=="":
        subprocess.run(["reboot"])
    else:
        message = f"\n\n{grub_error_result}\n\n"
        message += "Grub-reboot errors. Did you run as root?"
        raise Exception(message)
    ###