Skip to content

Instantly share code, notes, and snippets.

@KiruyaMomochi
Last active June 15, 2023 06:48
Show Gist options
  • Save KiruyaMomochi/9df313c2abc55c1736d457d48abc0f54 to your computer and use it in GitHub Desktop.
Save KiruyaMomochi/9df313c2abc55c1736d457d48abc0f54 to your computer and use it in GitHub Desktop.
Update `systemd-boot` after kernel update
#!/bin/bash
#
# This is a simple kernel hook to populate the systemd-boot entries
# whenever kernels are added or removed.
#
# Modified from https://blobfolio.com/2018/replace-grub2-with-systemd-boot-on-ubuntu-18-04/
# The UUID of your disk.
# Note: if using LVM, this should be the LVM partition.
UUID=$(findmnt -n / -o UUID)
# Any additional flags you wish to set.
DEFAULT_FLAGS=""
# Distribution pretty name.
. /etc/os-release
# Our kernels.
KERNELS=()
FIND="find /boot -maxdepth 1 -name 'vmlinuz-*' -type f -not -name '*.dpkg-tmp' -print0 | sort -Vrz"
while IFS= read -r -u3 -d $'\0' LINE; do
KERNEL=$(basename "${LINE}")
KERNELS+=("${KERNEL:8}")
done 3< <(eval "${FIND}")
# There has to be at least one kernel.
if [ ${#KERNELS[@]} -lt 1 ]; then
echo -e "\e[2msystemd-boot\e[0m \e[1;31mNo kernels found.\e[0m"
exit 1
fi
rm -rf /boot/efi/loader/entries/ubuntu*.conf
rm -rf /boot/efi/ubuntu
mkdir /boot/efi/ubuntu
# Copy kernel and write systemd-boot entry.
create_entry() {
NAME="$1"
SUFFIX="$2"
FLAGS="$3"
# Set default flags.
if [ -z "${FLAGS}" ]; then
FLAGS="${DEFAULT_FLAGS}"
fi
# Set title of boot entry.
if [ -n "$NAME" ]; then
TITLE="${PRETTY_NAME} (${NAME})"
NAME="-${NAME}"
else
TITLE="${PRETTY_NAME}"
fi
echo -e "\e[2msystemd-boot\e[0m \e[1;32m${TITLE}\e[0m ${FLAGS}"
# Find real kernel.
REAL_KERNEL=$(realpath /boot/vmlinuz${SUFFIX} | cut -c 15-)
if [ -n "$REAL_KERNEL" ]; then
REAL_SUFFIX="-$REAL_KERNEL"
else
REAL_SUFFIX="$SUFFIX"
fi
# Copy kernel and initramfs.
for FILE in initrd.img vmlinuz config System.map; do
cp "/boot/${FILE}${REAL_SUFFIX}" "/boot/efi/ubuntu/${FILE}${REAL_SUFFIX}"
done
# Create systemd-boot entry.
cat << EOF > /boot/efi/loader/entries/ubuntu${NAME}.conf
# This file is generated by zz-update-systemd-boot. Do not edit.
# Instead, edit /etc/kernel/postinst.d/zz-update-systemd-boot and rerun it.
title ${TITLE}
linux /ubuntu/vmlinuz${REAL_SUFFIX}
initrd /ubuntu/initrd.img${REAL_SUFFIX}
options root=UUID=${UUID} ro ${FLAGS}
EOF
}
LATEST="${KERNELS[@]:0:1}"
create_entry "" "-${LATEST}"
create_entry nohz_full "-${LATEST}" "isolcpus=1-63,65-127 nohz_full=1-63,65-127"
for VERSION in "${KERNELS[@]}"; do
create_entry "${VERSION}" "-${VERSION}"
done
# Success!
echo -e "\e[2m---\e[0m"
exit 0
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment