One-liner to clean DNF package cache but keep latest version of each package

If you’re running Fedora or Red Hat and have turned on the DNF package cache, eventually you’ll start using gigabytes of disk space. Simply running dnf clean packages will erase everything in the package cache.

But what if you want to preserve the latest version of each package and just delete the outdated versions? For example, to keep a local cache of the latest version of each package you’ve installed, and so that DRPM will still work on your next dnf upgrade.

Here’s how:

find /var/cache/dnf -maxdepth 2 -type d -name 'packages' -print0 | xargs -0 -n 1 -P 4 sh -c 'cd $1; for x in `ls *.rpm | grep -Po "^.*?(?=-[0-9])" | sort -ru`; do ls $x-*.rpm | egrep "^$x-[0-9]" | head -n -1 | xargs rm -f; done' sh

Disk space used before and after on my laptop:

du -hs /var/cache/dnf
7.5G	/var/cache/dnf
# run one-liner above
du -hs /var/cache/dnf
1.8G	/var/cache/dnf

Filed under: Blog, Code, Systems.  Tagged: , .