Skip to content

Instantly share code, notes, and snippets.

@HackingGate
Last active September 4, 2025 12:48
Show Gist options
  • Save HackingGate/ce56647c87fc8a4131cd8e9b67615966 to your computer and use it in GitHub Desktop.
Save HackingGate/ce56647c87fc8a4131cd8e9b67615966 to your computer and use it in GitHub Desktop.
#!/usr/bin/env bash
set -euo pipefail
# Check if running as root, if not, re-run with sudo
if [ "$EUID" -ne 0 ]; then
echo "This script needs to read grub.cfg and modify boot settings."
echo "Re-running with sudo..."
exec sudo "$0" "$@"
fi
# 0) Pick grub.cfg path (prefer grub2 layout)
if [ -r /boot/grub2/grub.cfg ]; then
CFG="/boot/grub2/grub.cfg"
elif [ -r /boot/grub/grub.cfg ]; then
CFG="/boot/grub/grub.cfg"
else
echo "Could not find grub.cfg under /boot/grub2 or /boot/grub" >&2
exit 1
fi
# 1) Read every top‑level menuentry title (handles leading whitespace & both quote styles)
mapfile -t ENTRIES < <(
grep -E "^[[:space:]]*menuentry [\"'].*[\"']" "$CFG" \
| sed -E "s/^[[:space:]]*menuentry [\"']([^\"']+)[\"'].*/\1/"
)
if [ ${#ENTRIES[@]} -eq 0 ]; then
echo "No GRUB entries found in $CFG" >&2
exit 1
fi
# 2) Print numbered menu
echo "Select which OS (or kernel) to boot *next* time only:"
for i in "${!ENTRIES[@]}"; do
printf " %2d) %s\n" "$i" "${ENTRIES[$i]}"
done
echo
# 3) Prompt
read -rp "Enter choice number: " CHOICE
# 4) Validate
if ! [[ "$CHOICE" =~ ^[0-9]+$ ]] || (( CHOICE < 0 || CHOICE >= ${#ENTRIES[@]} )); then
echo "Invalid selection." >&2
exit 1
fi
# 5) Find the proper grub reboot command
if command -v grub-reboot >/dev/null 2>&1; then
GRUB_REBOOT_CMD="grub-reboot"
elif command -v grub2-reboot >/dev/null 2>&1; then
GRUB_REBOOT_CMD="grub2-reboot"
else
echo "Neither grub-reboot nor grub2-reboot found in PATH." >&2
exit 1
fi
# 6) Reboot into the selected title
TITLE="${ENTRIES[$CHOICE]}"
echo "Will reboot into \"$TITLE\" on next boot…"
"$GRUB_REBOOT_CMD" "$TITLE"
reboot
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment