Skip to content

Instantly share code, notes, and snippets.

@tristone13th
Created August 8, 2022 01:15
Show Gist options
  • Save tristone13th/4e782b8e53d4ad7b29aacbd60c0b89c4 to your computer and use it in GitHub Desktop.
Save tristone13th/4e782b8e53d4ad7b29aacbd60c0b89c4 to your computer and use it in GitHub Desktop.
This snippet can help you change your grub default kernel when booting up.
import subprocess
import os
import sys
import re
if os.geteuid() != 0:
subprocess.call(['sudo', 'python3', *sys.argv])
sys.exit()
output = subprocess.check_output(
("cat", "/boot/grub/grub.cfg")).decode("iso-8859-1")
output = output.splitlines()
display_options = []
options = []
digit1 = -1
digit2 = -1
displaynr = -1
for line in output:
# +? denotes non-greedy search
res = re.fullmatch(
r"^(\t?)menuentry '(.+?)'.*$", line)
if res:
displaynr += 1
if res.group(1):
display_options.append(("\t" + res.group(2), displaynr))
digit2 += 1
options.append((res.group(2), f"{str(digit1)}>{str(digit2)}"))
else:
digit2 = -1
display_options.append((res.group(2), displaynr))
digit1 += 1
options.append((res.group(2), str(digit1)))
else:
res = re.fullmatch(
r"^submenu '(.+?)'.*$", line)
if res:
digit2 = -1
display_options.append((res.group(1), -1))
digit1 += 1
ljust = 3 if displaynr > 9 else 2
for i, option in enumerate(display_options):
if option[1] != -1:
print(f"[{option[1]}".ljust(ljust) + f"] {option[0]}")
else:
print(" " * ljust + f" {option[0]}")
option = int(input("\nPick one: "))
selection = options[option]
print(f"Your choice: {selection[0]}")
grub = open("/etc/default/grub", 'r')
lines = grub.readlines()
for i, line in enumerate(lines):
if re.match(r"^GRUB_DEFAULT=.*$", line):
lines[i] = "GRUB_DEFAULT=\"" + selection[1] + "\"\n"
grub = open("/etc/default/grub", 'w')
grub.writelines(lines)
grub.close()
subprocess.run(("update-grub"))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment