如何查看状态apt-get update
?
$ apt-get update ; echo "status is: $?"
Err http://security.debian.org stable/updates Release.gpg
Could not resolve 'security.debian.org'
Hit http://192.168.1.100 stable Release.gpg
Hit http://192.168.1.100 stable Release
Hit http://192.168.1.100 stable/main i386 Packages
Hit http://192.168.1.100 stable/contrib i386 Packages
Hit http://192.168.1.100 stable/non-free i386 Packages
Ign http://192.168.1.100 stable/contrib Translation-en
Ign http://192.168.1.100 stable/main Translation-en
Ign http://192.168.1.100 stable/non-free Translation-en
Reading package lists... Done
W: Failed to fetch http://security.debian.org/dists/stable/updates/Release.gpg Could not resolve 'security.debian.org'
W: Some index files failed to download. They have been ignored, or old ones used instead.
status is: 0
Run Code Online (Sandbox Code Playgroud)
此处获取安全更新时出错,但退出状态为 0
我的目标是编写一个脚本来检查 apt-get update 是否正确运行。
小智 13
使用这个 apt 选项将这些警告变成错误:
apt-get update -o APT::Update::Error-Mode=any
Run Code Online (Sandbox Code Playgroud)
如果您愿意,您也可以在conf 文件中进行设置。
在您的示例中,apt-get update
没有错误退出,因为它将问题视为警告,而不是致命的错误。如果有一个真正致命的错误,那么它将以非零状态退出。
识别异常的一种方法是检查以下模式stderr
:
W:
是警告E:
是错误如果上述模式匹配,或者apt-get update
自身的退出代码非零,您可以使用类似的方法来模拟失败:
if ! { sudo apt-get update 2>&1 || echo E: update failed; } | grep -q '^[WE]:'; then
echo success
else
echo failure
fi
Run Code Online (Sandbox Code Playgroud)
请注意!
在if
。这是因为grep
如果模式匹配,则成功退出,也就是说,如果有错误。当没有错误时,grep
它本身就会失败。所以if
条件是否定grep
.