As time goes by and you keep installing more and more updates on a Linux machine, it will eventually get cluttered with all the kernels it has ever left behind. Probably the only time these can come in handy is when you can’t boot into a new kernel right after an upgrade.
The following command, which really is better than it looks, will remove all the previous kernel images, headers and modules that can and will take up precious disk space, leaving only the current one intact:
dpkg -l 'linux-*' | sed '/^ii/!d;/'"$(uname -r | sed "s/\(.*\)-\([^0-9]\+\)/\1/")"'/d;s/^[^ ]* [^ ]* \([^ ]*\).*/\1/;/[0-9]/!d' | xargs sudo apt-get -y purge
This can be useful on a server that performs automatic system-side incremental backups to an external storage device. Running this command will help delay that “dafuq” moment when the backup sizes exceed the storage capacity of the external drive.
Now, for the sake of any impending F*CKs, imagine how dumb it would be to run this command on a system that just had an update with a new kernel and hasn’t been rebooted yet…