Create a gist now

Instantly share code, notes, and snippets.

This script cleans out old kernels on Ubuntu.
#!/usr/bin/perl -w
use strict;
my $kernel_version = `uname -r`;
my @kernel = (0,0,0,0);
if($kernel_version =~ /((\d+).(\d+).(\d+)-(\d+))/) {
$kernel_version = $1;
$kernel[0] = $2;
$kernel[1] = $3;
$kernel[2] = $4;
$kernel[3] = $5;
}
# This value is used for comparison later on
my $k = sprintf("%04d%04d%04d%04d", @kernel);
my $tmp = join(".", @kernel);
print "Kernel Version: $kernel_version ($tmp)\n";
my $raw_output = `dpkg -l linux-* | grep '^ii' | awk '{print \$2}'`;
my @package_list = split("\n", $raw_output);
my @remove = ();
foreach my $package(@package_list) {
if($package =~ /(linux-([a-z]*-)+((\d+).(\d+).(\d+)-(\d+)).*)/) {
my $package_name = $1;
my $package_version = $3;
my @version = (0,0,0,0);
$version[0] = $4;
$version[1] = $5;
$version[2] = $6;
$version[3] = $7;
my $v = sprintf("%04d%04d%04d%04d", @version);
if ($v < $k) {
$tmp = join(".", @version);
print "Removing Package: $package_name\tVersion: $package_version ($tmp)\n";
push @remove, $package_name;
}
}
}
print "\n";
my $cmd = "sudo apt-get -y remove " . join(" ", @remove);
print $cmd, "\n";
exec $cmd
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment