Conditional OS selection with GRUB
This is a little hack that allows you to multi-boot comfortably without having to wait for the bootloader menu and deal with unnecessary reboots in case you missed it. My use case is a headless PC that either runs Windows with a VR headset attached or Linux to serve SSH sessions as a GPU-enabled development machine. To select the OS, I use a plain USB flash drive. If the flash drive is attached, Windows will boot, if not, the system defaults to Linux.
GRUB makes this setup possible by providing a minimal scripting environment. The search
command tries to find a certain device by label, path or UUID. We can check whether the flash drive is attached by searching for its UUID and checking the variable set by search:
# /etc/grub.d/40_custom
menuentry "Conditional Boot" {
# can be obtained with `blkid`
set usb_uuid=01234-ABCD
search --fs-uuid $usb_uuid --set=usb_root
if [ -n "$usb_root" ] ; then
# We detected the usb flash drive, boot Windows
# <Insert lines from Windows menuentry>
boot
else
# Flash drive not attached, boot Linux as usual
# <Insert lines from Linux menuentry>
boot
fi
}
I am hesitant to provide a step-by-step tutorial since blindly copy-and-pasting from Blogs into your bootloader configuration is probably not a great idea.
Caveats
Because the entries are inserted manually, it is the responsibility of the user to change boot parameters accordingly if they change with a system update.