從 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 命令,您可以使用fcntl 鎖用於鎖定的實用程式(Peter Anvin 的叢集命令的克隆,但稍微過時了)。

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

如果你想自動化,我認為使用系統路徑效果最好。

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

相關內容