Re: Script to remove old kernels
Quote:
Originally Posted by
oldfred
I do not know bash so I had to do a little research.
This worked for me, I had to add the echo to know what was what and remove the file name from the wc command.
Code:
#!/bin/bash
counter=2
ls /boot/ | grep vmlinuz | sed 's@vmlinuz-@linux-image-@g' | grep -v `uname -r ` > /tmp/kernelList
numberOfExtraKernels=`wc -l /tmp/kernelList | awk '{print $1}'`
for l in `cat /tmp/kernelList`
do
if [ "$counter" -lt "$numberOfExtraKernels" ]
echo "$l", "$counter", "$numberOfExtraKernels"
then
aptitude remove $l
let "counter +=1"
fi
done
rm -f /tmp/kernelList
update-grub
When I ran it with counter =1 it deleted all but 1, so now I cannot test with counter =2.
OK, this is useful enough that it could use a little improvement. What I have done in the following script is:
- remove the insecure temp file
- generate a list of kernels to keep
- increase permissions (sudo) only when needed
I call this script "purge-kernel"
Code:
#!/bin/bash
# Get a list of the kernels that are installed.
kernelList=$(cd /;ls boot/vmlinuz*)
# Make a list of the kernels to keep. These are the kernels linked to by /vmlinuz,
# /vmlinuz.old, and the currently running kernel.
keepList="$(readlink -q /vmlinuz) $(readlink -q /vmlinuz.old) boot/vmlinuz-$(uname -r)"
# Change the list of file names to list of package names.
kernelPkg=$(sed 's@boot/vmlinuz-@linux-image-@g' <<<$kernelList)
keepPkg=$(sed 's@boot/vmlinuz-@linux-image-@g' <<<$keepList)
# Create a list of packages to purge. This is the list of installed kernels with the kernels
# to keep removed.
purgePkg=${kernelPkg}
for keep in $keepPkg
do
eval purgePkg=\${purgePkg/$keep}
done
purgePkg=$(echo $purgePkg) # Remove extra white space
echo "kernels to keep: $keepPkg"
# If there are any kernels to remove then purge them and update grub;
if [ -n "${purgePkg}" ]
then
tmpfile=$(mktemp)
chmod +x $tmpfile
echo "dpkg --purge ${purgePkg};update-grub"
echo "dpkg --purge ${purgePkg};update-grub" > $tmpfile
sudo -s $tmpfile
sleep 1 # following 'rm' fails otherwise.
rm -f $tmpfile
else
echo "No kernels to purge."
fi
exit
Re: Script to remove old kernels
I'm sorri i know this is a veri old post but i'm looking for a script for this job. I 've run this script setting the counter on 6! and it deletes all the kernels but the last one. Could it be the "let" sentence, i dont know its functioning.
Re: Script to remove old kernels
May I suggest a much easier script for this? It will keep only two latest kernels although.
Re: Script to remove old kernels
From the Ubuntu Forums Code of Conduct.
Quote:
If a post is older than a year or so and hasn't had a new reply in that time, instead of replying to it, create a new thread. In the software world, a lot can change in a very short time, and doing things this way makes it more likely that you will find the best information. You may link to the original discussion in the new thread if you think it may be helpful.
Thread closed.