You have a Debian, Ubuntu or similar installation, and your
/var partition keeps getting full when you upgrade. You check
/var/cache/apt/archives and ﬁnd it full of the usual mix of current and old versions of downloaded packages. Somehow, they haven't been deleted after installation, or you keep downloading them but not installing them. You now need a quick and clever way of cleaning up this mess, so only the latest version of each package remains.
Here's an appropriate bash invocation:
For each package name, this will delete all but the latest
.deb package. Obviously, if there's only one version of a package, it's not deleted. You will be asked to conﬁrm each deletion.
sudofrom the second line. On Ubuntu,
sudois already set up for you, and you should use it. On Debian, you need to install and set it up yourself.
Debian package names can't contain an underscore (
_). Everything that comes after the underscore in a
.deb ﬁlename is version (and platform) information. The back-quoted part of the ﬁrst line locates all package name stems. By performing
ls | grep rather than using something like
ls /var/cache/apt/archives/*.deb, we avoid failure in case there are too many packages for the command line1.
Then, on the second line, we list everything that starts with that package name, order it by increasing timestamp (latest ﬁles last), and use
sed to delete the last line (most recent ﬁle). All ﬁlenames thus nominated are deleted using the
xargs sudo rm invocation. The
-r option avoids running
sudo rm with no arguments.
This script runs
rm verbosely and interactively, using the
xargs) options respectively. Every deletion is printed out, and you're asked to conﬁrm each one. Then, the actual deletions are printed out. If this gets too much (it often does), remove the
-v option. To remove interactivity and delete without checking, just remove the
xargs (or insert
yes | before the
for keyword on the ﬁrst line).
- 1. On Linux, the maximum command line length varies. Before Linux 2.6.23, it used to be 131,072 bytes. Starting with Linux 2.6.23, there is no limit in the kernel, but it still reports the traditional limit anyway (tell bash
getconf ARG_MAXto ﬁnd out what it is). We shouldn't rely on this.