Score:0

Delete .deb files of Removed packages from apt-cache

cn flag

apt-get autoclean deletes outdated .deb files from /var/cache/apt/archives directory which are no longer available or cannot be downloaded anymore.

whereas apt-get clean deletes each and every .deb file located in /var/cache/apt/archives directory.

I want to delete the .deb files of only those packages which are no longer installed, have been uninstalled or removed. How to do this?

user535733 avatar
cn flag
I suppose you could take the output of `sudo apt-mark showremove`, fiddle with the formatting a bit, and plug that list into `sudo apt clean`
Score:0
cn flag

APT relies on fcntl(2) locking; since ubuntu does not provide an fcntl lock command, you may use fcntl-lock utility for locking (a clone of Peter Anvin's flock command, slightly outdated, though).

#!/bin/bash

apt_cache=/var/cache/apt/archives

# Link: https://github.com/magnumripper/fcntl-lock
# fcntl-lock is a fcntl() clone of H. Peter Anvin's flock(1)
coproc LOCK {
    exec fcntl-lock \
    -x -w 3600 "$apt_cache/lock" -c 'echo true; exec cat'
}
read -ru ${LOCK[0]} || { \
    echo Failed to obtain a lock.
    exit 1
}

declare -a a=()
declare -A A=() B=()

# URL decode .deb filenames.
cd "$apt_cache"
for b in *.deb; do
    printf -v c %b "${b//%/\\x}"; A[$c]=$b
done

# You may use @(rc|ii) to add more Abbrev's
while read -r d e; do
    [[ $d = ii ]] && B[$e]=1
done < <( \
    dpkg-query \
        -Wf='${db:Status-Abbrev} ${Package}_${Version}_${Architecture}.deb\n' \
)

for f in "${!A[@]}"; do
    [[ ${B[$f]} = 1 ]] || \
        a+=("$apt_cache/${A[$f]}")
done
((${#a[@]} > 0)) && \
    printf %s\\0 "${a[@]}" | xargs -0 rm -v || exit 0

# echo Success | ts >> /var/log/apt-archive-clean.log

If you want to automate, I think using systemd.path works best.

apt-archive-clean.path

[Unit]
Description=APT Archive Cleanup

[Path]
PathChanged=/var/cache/apt/archives/lock

[Install]
WantedBy=multi-user.target

apt-archive-clean.service

[Unit]  
Description=APT Archive cleanup  
  
[Service]  
Type=simple  
ExecStart=/opt/bin/apt-archive-clean.sh
mangohost

Post an answer

Most people don’t grasp that asking a lot of questions unlocks learning and improves interpersonal bonding. In Alison’s studies, for example, though people could accurately recall how many questions had been asked in their conversations, they didn’t intuit the link between questions and liking. Across four studies, in which participants were engaged in conversations themselves or read transcripts of others’ conversations, people tended not to realize that question asking would influence—or had influenced—the level of amity between the conversationalists.