purge-old-kernels: an attempt at a successor

About writing shell scripts and making the most of your shell
Forum rules
Topics in this forum are automatically closed 6 months after creation.
Locked
User avatar
Pjotr
Level 24
Level 24
Posts: 20090
Joined: Mon Mar 07, 2011 10:18 am
Location: The Netherlands (Holland) 🇳🇱
Contact:

purge-old-kernels: an attempt at a successor

Post by Pjotr »

The nifty Ubuntu script purge-old-kernels (part of the byobu package) has been deprecated for Ubuntu versions after 16.04, because apt autoremove should do the same job.

For those of us who want to keep this precision instrument, I've forked it here:
https://github.com/Pjotr123/purge-old-kernels-2

Any improvement suggestions are welcome, both at GitHub and here. :)

Note: as you can still install purge-old-kernels in Mint 18.x (by installing byobu), this'll only become useful in Mint 19. Well, maybe now already, if you don't want to install byobu....

---Edit: I've tried to make it even easier to use, with this how-to:
https://sites.google.com/site/easylinux ... one-stroke
(item 6.1, right column)
Last edited by LockBot on Wed Dec 28, 2022 7:16 am, edited 1 time in total.
Reason: Topic automatically closed 6 months after creation. New replies are no longer allowed.
Tip: 10 things to do after installing Linux Mint 21.3 Virginia
Keep your Linux Mint healthy: Avoid these 10 fatal mistakes
Twitter: twitter.com/easylinuxtips
All in all, horse sense simply makes sense.
User avatar
Termy
Level 12
Level 12
Posts: 4248
Joined: Mon Sep 04, 2017 8:49 pm
Location: UK
Contact:

Re: purge-old-kernels: an attempt at a successor

Post by Termy »

Here are some things I'd like to suggest, and would do myself:

- Add support for linux-image-extra-*.
- Rework the logic so awk isn't needed, to avoid an additional dependency.
- Add dep testing and test for supported system with $OSTYPE and lsb_release.
- Use apt-get by default (more features) but offer flag for apt use.
- Maybe add add --type=x, where x is the type of kernel. Disregard type by default.
- Provide short option(s).
- Provide --help or --usage information.
- Provide some verbosity; error messages and such.
- Use direct paths as a security measure.
- Maybe use bash, so you could use extglob, brace expansion, and bash variables, such as UID.

I'd love to see any changes you make to the script.
I'm also Terminalforlife on GitHub.
User avatar
Pjotr
Level 24
Level 24
Posts: 20090
Joined: Mon Mar 07, 2011 10:18 am
Location: The Netherlands (Holland) 🇳🇱
Contact:

Re: purge-old-kernels: an attempt at a successor

Post by Pjotr »

Thanks for responding! :)

Unfortunately, my coding skills are very small. In Linux, I'm purely a layman with some teaching skills (hence my focus on improving the how-to). So I can only try to address a few of your suggestions. Here goes:
Termy wrote:Here are some things I'd like to suggest, and would do myself:

- Add support for linux-image-extra-*.
Please bear in mind that I'm only a layman, but isn't that already covered by this: {print "linux-image-" $0 " linux-headers-" $0}?

Or do we need to add the wildcard *, so it becomes {print "linux-image-*" $0 " linux-headers-" $0}? Or even {print "linux-image-*" $0 " linux-headers-*" $0}?
- Rework the logic so awk isn't needed, to avoid an additional dependency.
AFAIK, awk is part of the default Linux Mint installation. If I'm right in that assumption, this means that this particular dependency is probably not cumbersome....

The other things: could you perhaps fork the script on GitHub into e.g. purge-old-kernels-3, and showcase your suggestions?
Tip: 10 things to do after installing Linux Mint 21.3 Virginia
Keep your Linux Mint healthy: Avoid these 10 fatal mistakes
Twitter: twitter.com/easylinuxtips
All in all, horse sense simply makes sense.
User avatar
Termy
Level 12
Level 12
Posts: 4248
Joined: Mon Sep 04, 2017 8:49 pm
Location: UK
Contact:

Re: purge-old-kernels: an attempt at a successor

Post by Termy »

I don't have an account on GitHub, but I'll set one up, with a contact E-Mail address I'll use on all my projects. I would have had to use it eventually, as I've got projects piling up just itching to be shared. lol

You can find what I've called roks (I've mentioned what prompted me to write it :) ) here:

https://github.com/terminalforlife/roks

I'm completely new to GitHub (at least as far as having an account), so if I've done something silly, please let me know!

Moments later...

I forgot to address your questions. I guess I was more thinking of roks as I intend it to be viable on more than just Mint. I'm a big fan of dep checking and using as few non-essentials as possible. If you can do it with a builtin, it has a chance to be faster, and it's more portable. This has at least been my experience and what I've learned from others. As for linux-image-extras, I'm looking into that now, but I'm pretty sure it would be best to specify all, or at least provide the option to. I'm a big fan of options too; giving the user the power to do what they want; I always love that in a program. :)

By the way, I forgot last night that apt in Mint is different to apt in other places, so, since apparently apt in Mint is a python wrapper for apt-get, apt-cache, etc, that would mean my using apt-get by default isn't necessarily the better move, at least in Mint, but I can't see it being harmful.

I forked it, thinking it with something else, but I totally did the wrong thing. I hate GitHub >.< but I'm sure I'll figure it all out eventually. I have no idea how to suggest changes to what you have. I thought committing was posting a change, which can then be revised and possibly put forward by the person(s) behind the repository. Sorry if I caused any confusion. :oops:

Oh, oh, and and (lol) I believe you're right about awk being part of Mint by default; I've yet to see a Mint setup without it, but then the user can just remove it, or have some other sort of custom setup; this is why I don't like to assume too often.
I'm also Terminalforlife on GitHub.
User avatar
Termy
Level 12
Level 12
Posts: 4248
Joined: Mon Sep 04, 2017 8:49 pm
Location: UK
Contact:

Re: purge-old-kernels: an attempt at a successor

Post by Termy »

Finally finished roks. Took a while because I ran into an issue that took a while to figure out. In the end, since the original code on which I based a part of my own approach was faulty, I had to come up with something myself, while stubbornly trying to ensure it's portability, speed, and efficiency; it's now gone 1am. lol

Can't remember if I posted the link, but here it is: https://github.com/terminalforlife/roks

For details:

The issue with what you've forked is that the whole head approach is broken. I tested the heck out of it, my approach and the original, and could not get it to work properly. I installed 3 more kernels to test it (4 total) and it just refused to process, for example, the last 2 kernels, if I went with the default of 2. If I chose 3, it wouldn't remove the remaining 1. It was very unreliable.

I didn't have particularly bizarre kernels, just 4 *-generic ones:

Code: Select all

➤  sudo sh -c "ls -tr /boot/vmlinuz-*"
/boot/vmlinuz-4.10.0-30-generic  /boot/vmlinuz-4.4.0-92-generic
/boot/vmlinuz-4.11.0-14-generic  /boot/vmlinuz-4.4.0-93-generic
Now I'll use roks to remove the old kernels, and optionally apply --purge and/or --autoremove. It's more flexible than using --autoremove to remove kernels, I think.

I wonder if the behavior of head or something else used in the original logic was changed with some update which messed it up. In any case, I've got it sorted in roks, so I'm sure a similar or same approach can be done in your purge-old-kernels-2.

If you or someone else could test roks in your systems (Mint 18.2 especially, but any would do) that would be cool. Use the -s flag to have it simulate, if you're unsure.
I'm also Terminalforlife on GitHub.
Misko_2083

Re: purge-old-kernels: an attempt at a successor

Post by Misko_2083 »

Few years ago, I made some scripts with zenity dialogs as UI for Linux Lite. This was the bash function for removing old kernels:

Code: Select all

KERNELS() {
APPNAME=" Kernel Remover"
# Check current Kernel
CURKERNEL=$(uname -r|sed 's/-*[a-z]//g'|sed 's/-386//g')
# Define what Kernel packages to look for
LINUXPKG="linux-(image|headers|firmware-image|ubuntu-modules|restricted-modules)"
METALINUXPKG="linux-(image|headers|firmware-image|restricted-modules)-(generic|i386|i686|server|common|rt|xen)"
# Find old Kernels
OLDKERNELS=$(dpkg -l|awk '{print $2}' | grep -E $LINUXPKG | grep -vE $METALINUXPKG | grep -v $CURKERNEL)
# Check if there are old Kernels
echo $OLDKERNELS | grep linux*
  if [ "${PIPESTATUS[1]}" -ne "0" ]; then
        zenity --info --width="225" --height="60" --title=" $APPNAME - Information" --text="\nNo additional kernels were found in your system for removal." 2>/dev/null; return
  fi
# sed command adds all FALSE entries in the column 'Select'
zen=(`echo "$OLDKERNELS" | sort -t. -k1,1n -k2,2n | sed -e  's/^/FALSE\n/'`)

# Main dialog window
DIALOG_TEXT='<span font="Sans 10">  For each kernel version to remove, select its:\n\n    <b>headers</b>\n    <b>image</b>\n    <b>image-extra</b>\n    <b>firmware</b> (if any)</span>\n
<span font="Sans 9">  The removal process will not begin until your selection\n  is reviewed and confirmed.</span>\n'

# Call the dialog. Don't change the separator here!
okernel=$(zenity --window-icon="$_ICON" --list --checklist --separator=" " --width=360 --height=400 --column="Select" --column="Kernels available for removal" \
                 --text="${DIALOG_TEXT}" --title="$APPNAME" --ok-label="Remove" "${zen[@]}" 2>/dev/null)
  if [ "${PIPESTATUS[0]}" -ne "0" ]; then return; fi # If cancel is clicked then exit

  # Check if anything is selected
  echo $okernel | grep linux*
  if [ "${PIPESTATUS[1]}" -ne "0" ]; then
    zenity --info --width="260" --height="60" --window-icon="$_ICON" --title=" $APPNAME" --ok-label="Go Back" \
           --text="\nNo kernel headers and image were selected for removal. Try again." 2>/dev/null; continue
  fi

  # Split kernel selection
  selection_array=($okernel)
  KN_NAMES=""
  for ((i=0; i<${#selection_array[@]}; ++i)); do
    KN_NAMES=$KN_NAMES"✔ "${selection_array[$i]}"\n"
  done
  # Confirm kernel selection removal
SHOWPROGREM=$(grep '^deb' -c /etc/apt/sources.list)
  zenity --question --window-icon="$_ICON" --width="280" --height="60" --title=" $APPNAME"  --text="\nYou are about to remove:<b>\n\n$KN_NAMES </b>\nDo you want to proceed?" 2>/dev/null
  if [ "$?" -eq "0" ]; then
    echo "Removing kernels: ${okernel}" | tee "$_LTLOGS"
    apt-get purge -y $okernel |
    awk -v total=$SHOWPROGREM '/^Ign|^ Get/{count++;$1=""} FNR { if (total != 0){percentage=int (1000*count/total);print (percentage < 90?percentage:99),"\n#",substr($0, 0, 128) }; fflush(stdout)}' |
    tee -a "$_LTLOGS" | zenity --progress --width="620" --height="80" --window-icon="$run_icon" --title=" $APPNAME" --percentage="0" --no-cancel --pulsate --auto-close --auto-kill \
                               --text="Removing selected kernels, please wait..." 2>/dev/null
    if [ "${PIPESTATUS[0]}" -ne "0" ]; then
      _FAILURE=$(zenity --question --icon-name="error" --window-icon="error" --width="240" --height="60" --title="$APPNAME Error" \
                        --text="\nAn error occurred while removing selected kernels.\n\nWould you like to review the logs?" 2>/dev/null ; echo $?)
      sed -i '1 i\===========================\
Kernel Remover Error log\
===========================\
An error occurred while removing selected kernels.\
Go to https://www.linuxliteos.com/forums/ and paste the log below into a new or existing thread for assistance.\n\
============ Log ===========\n' "$_LTLOGS"
      sed -i '/^\<0\>[[:space:]]/d' "$_LTLOGS"
      VIEW_SAVE_LOG; return
    else
      zenity --info --width="270" --title="$APPNAME" --window-icon="$_ICON" --text="\nSelected kernels were successfully removed." 2>/dev/null; rm -f "$_LTLOGS"; return
    fi
fi
}
User avatar
Termy
Level 12
Level 12
Posts: 4248
Joined: Mon Sep 04, 2017 8:49 pm
Location: UK
Contact:

Re: purge-old-kernels: an attempt at a successor

Post by Termy »

Lord almighty... please tell me the formatting got messed up in transit. That's really quite chaotic. :? Love the awk stuff.
I'm also Terminalforlife on GitHub.
Locked

Return to “Scripts & Bash”