CentOS 7 learn used grub entry

With the major changes introduced in CentOS 7 from CentOS 6 (systemd, grub2, and more), determining exactly which grub menu entry will be used at next boot is a little more difficult than before.

I wrote a quick script that calculates this for you: learn-used-grub-entry

#!/bin/sh
# File: learn-used-grub-entry
# Location: /usr/bin
# Author: bgstack15
# Startdate: 2019-01-28 11:27
# Title: Script that Determines Which Grub Entry Will be Used
# Purpose:
# Package: bgscripts
# History:
# Usage:
#    for RHEL7/grub2
# Reference:
#    original research
# Improve:

test -z "${LUGE_GRUB_CFG}" && LUGE_GRUB_CFG=/boot/grub2/grub.cfg
test -z "${LUGE_ETC_DEFAULT_GRUB}" && LUGE_ETC_DEFAULT_GRUB=/etc/default/grub
# use option LUGE_OUTPUT which is one of ["kernel","","initram"]

grub_saved_name="$( grub2-editenv - list | awk -F'=' '{print $NF}' )"
use_number="$( awk -F'=' '/^GRUB_DEFAULT/{print $NF}' "${LUGE_ETC_DEFAULT_GRUB}" )"

use_entry=""
# calculate true value
if test "$( echo "${use_number}" | tr '[[:upper:]]' '[[:lower:]]' )" = "saved" ;
then
   # it is the saved value (which is same as last used)
   use_entry="${grub_saved_name}"
else
   # calculate used name from number
   use_entry="$( grep -E -e '^menuentry' "${LUGE_GRUB_CFG}" | sed -r -n -e "$(( use_number + 1 ))p" )"
fi

# calculate which value to display or just display name
LUGE_grep=1
case "${LUGE_OUTPUT:-${1}}" in

   "num" | "number" )
      # just show the number
      unset LUGE_grep
      echo "${use_number}"
      ;;

   "kernel"|"vmlinuz" )
      # show kernel
      LUGE_regex="linux(16|32|64)"
      LUGE_awk_val='$2'
      ;;

   "initram" | "initrd" | "initramfs" )
      # show initram
      LUGE_regex="initrd|initram"
      LUGE_awk_val='$2'
      ;;

   *)
      # DEFAULT VALUE, so mistyped or not defined
      unset LUGE_grep
      echo "${use_entry}"
      ;;
esac

# show complicated value if necessary
if test -n "${LUGE_grep}" ;
then
   sed -n -r -e "/${use_entry}/,/^\s*\}/p" "${LUGE_GRUB_CFG}" | awk "/${LUGE_regex}/{print ${LUGE_awk_val}}"
fi

# exit cleanly
true
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.