How to choose different systems, based on pressed key in GRUB2

Ok, so the Internet is crawling with plenty of howtos for configuring different/many operating systems during boot with GRUB2. But I haven’t found the single one, how to make it depended on simple key press – not have to choose from GRUB menu.

So, in my case, I want to have boot up Linux/Debian all the time – as the default system, but from time to time, use Windows for Fusion 360 (or for gaming). Of course I can choose different OS from GRUB menu – like everyone else, but it would be much nicer and faster to simply press “shift” during boot and see Windows.

And yes, we can do it 🙂

The only thing we need to do, is to edit grub script file. In Debian (and probably all other clones like Ubuntu) this file is splitted in few smaller ones in /etc/grub.d directory.

root@homee:/etc/grub.d# ls -l
total 76
-rwxr-xr-x 1 root root  9783 Oct 31  2016 00_header
-rwxr-xr-x 1 root root  6258 Jan 22  2016 05_debian_theme
-rwxr-xr-x 1 root root 12444 Oct 29 14:02 10_linux
-rwxr-xr-x 1 root root 11497 Oct 29 14:02 20_linux_xen
-rwxr-xr-x 1 root root 12059 Oct 31  2016 30_os-prober
-rwxr-xr-x 1 root root  1418 Sep  4  2015 30_uefi-firmware
-rwxr-xr-x 1 root root   328 Nov 27 21:43 40_custom
-rwxr-xr-x 1 root root   216 May  9  2013 41_custom
-rw-r--r-- 1 root root   483 Apr 15  2011 README

We can now edit 40_custom and add this small snipped

if keystatus -s ; then
    set default='Windows 10 (on /dev/sda2)'
    set timeout=10
else
    set timeout=10
fi

This will make GRUB to boot to alternative OS – in this case Windows 10 – if you press “shift” during startup. You can also add additional commands here and check for other keys (like ctrl or alt). You can of course, set timeout to 0 and erase else statement – this is just for demonstration purpose.

Now you need to regenerate grub.cfg file and update grub. That’s it!

grub-mkconfig -o /boot/grub/grub.cfg
update-grub

Bonus stuff 🙂

Additionally, if you want to list all possible menu entries (without recovery and safe boot) use this:

root@homee:~# grep -i 'menuentry ' /boot/grub/grub.cfg|cut -d"'" -f2 | grep -vi recovery | grep -v sysvinit
Debian GNU/Linux
Debian GNU/Linux, with Linux 4.15.0-3-amd64
Windows 10 (on /dev/sda2)

If you want only during next boot to start Windows, set next boot with command (your grub “default” has to be set to “saved”) and reboot:

grub-reboot "Windows 10 (on /dev/sda2)"

Dodaj komentarz

avatar
  Subscribe  
Notify of