从 apt-cache 中删除已移除软件包的 .deb 文件

从 apt-cache 中删除已移除软件包的 .deb 文件

apt-get autoclean从目录中删除不再可用或无法再下载的过时.deb文件。/var/cache/apt/archives

而删除目录中的apt-get clean每个文件。.deb/var/cache/apt/archives

我只想删除.deb那些不再安装、已被卸载或删除的软件包的文件。该怎么做?

答案1

APT 依赖于fcntl(2)锁定;由于 ubuntu 没有提供 fcntl lock 命令,您可以使用功能锁锁定实用程序(Peter Anvin 的 flock 命令的克隆,但稍显过时)。

#!/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

如果你想实现自动化,我认为使用systemd.path效果最好。

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

相关内容