LLI Wiki — My Digital Knowledge Base

Linux: detect whether a reboot is pending

Bash scripts to check whether a reboot is required on Ubuntu/Debian, CentOS/RHEL and Arch Linux.

These scripts check whether a reboot is pending after a kernel or library update. Choose the script that matches the distribution.

Ubuntu / Debian

Ubuntu and Debian create the file /var/run/reboot-required when a reboot is needed:

#!/bin/bash
if [ -f /var/run/reboot-required ]; then
    echo 'System needs to be rebooted'
fi

CentOS / RHEL

Compare the most recently installed kernel with the running kernel:

#!/bin/bash
LAST_KERNEL=$(rpm -q --last kernel | perl -pe 's/^kernel-(\S+).*/$1/' | head -1)
CURRENT_KERNEL=$(uname -r)

test $LAST_KERNEL = $CURRENT_KERNEL || echo REBOOT

Arch Linux

This script checks two cases: deleted libraries still loaded by running processes (DEL in lsof output), and a running kernel that differs from the kernel found in /boot. The exit code is 0 when a reboot is required.

#!/bin/bash

get_boot_kernel() {
    local get_version=0
    for field in $(file $(ls /boot/vmlinuz* -Art | tail -n 1)); do
        if [[ $get_version -eq 1 ]]; then
            echo $field
            return
        elif [[ $field == version ]]; then
            # the next field contains the version
            get_version=1
        fi
    done
}

rc=1

hostname

libs=$(lsof -n +c 0 2> /dev/null | grep 'DEL.*lib' | awk '1 { print $1 ": " $NF }' | sort -u)
if [[ -n $libs ]]; then
    cat <<< $libs
    echo "# LIBS: reboot required"
    rc=0
fi

active_kernel=$(uname -r)
current_kernel=$(get_boot_kernel)

if [[ $active_kernel != $current_kernel ]]; then
    echo "$active_kernel < $current_kernel"
    echo "# KERNEL: reboot required"
    rc=0
fi
exit $rc
Mastodon LLIMastodon SocialFosstodon