Last active
April 19, 2018 17:22
-
-
Save Thermionix/7797652 to your computer and use it in GitHub Desktop.
cron script for ubuntu servers to automatically purge old kernels,
quickly insert with; curl https://gist.github.com/Thermionix/7797652/raw/purge-old-kernels | bash
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/bash | |
cat <<-'EOF' | sudo tee /usr/local/sbin/purge-old-kernels | |
#!/bin/sh | |
#This script will keep the currently running kernel and 2 latest | |
export PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin | |
if [ "$(id -u)" != 0 ]; then | |
echo "ERROR: This script must run as root." 1>&2 | |
exit 1 | |
fi | |
CANDIDATES=$(ls -tr /boot/vmlinuz-* | head -n -2 | grep -v "$(uname -r)$" | cut -d- -f2- | awk '{print "linux-image-" $0}') | |
for c in $CANDIDATES; do | |
dpkg-query -s "$c" >/dev/null 2>&1 && PURGE="$PURGE $c" | |
done | |
if [ -z "$PURGE" ]; then | |
echo "No kernels are eligible for removal" | |
exit 0 | |
fi | |
apt-get -yq remove --purge $PURGE | |
EOF | |
sudo chmod 0744 /usr/local/sbin/purge-old-kernels | |
echo -e "5 1 1 * * root /usr/local/sbin/purge-old-kernels > /dev/null 2>&1\n" | sudo tee /etc/cron.d/purge-old-kernels | |
sudo chmod 0644 /etc/cron.d/purge-old-kernels |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment