Cor*_*ter 17 linux bash command-line-interface apt raspbian
我正在尝试编写一个脚本,该脚本将从 apt 输出可升级包的数量。然而,它也不断给我这个警告:
# sudo apt update | grep packages | cut -d '.' -f 1
WARNING: apt does not have a stable CLI interface. Use with caution in scripts.
All packages are up to date
Run Code Online (Sandbox Code Playgroud)
我希望它只输出:
All packages are up to date
Run Code Online (Sandbox Code Playgroud)
或者
35 packages can be updated
Run Code Online (Sandbox Code Playgroud)
有什么办法可以禁用该警告吗?我将在来自 cron 作业的 Discord 通知中使用这个返回的字符串以及一些额外的信息,它非常糟糕地搞乱了我的输出。
我已经看过这些,但没有一个对我有用:
https://unix.stackexchange.com/questions/19470/list-available-updates-but-do-not-install-them
https://askubuntu.com/questions/269606/apt-get-count-the-number-of-updates-available
Dav*_*man 15
首先,考虑您试图隐藏的警告的含义。从理论上讲,apt
明天可能会更改为将它们称为“分发版”而不是“包”(因为它“还没有稳定的 CLI 界面”),这将完全破坏您的管道。更可能的更改是在多个地方使用“包”一词,导致您的管道返回无关信息,而不仅仅是您正在查找的包计数。
但您可能不太担心这一点,而且实际上,您没有理由担心。界面多年来一直稳定,可能不会很快改变。那么如何让这个警告消失呢?
在 *nix 世界中,到命令行的输出通常有两种风格,stdout(标准输出)和 stderr(标准错误)。表现良好的程序将其正常输出发送到 stdout,并将任何警告或错误消息发送到 stderr。因此,如果您希望错误/警告消失,通常可以通过使用 output redirection 丢弃 stderr 上的任何消息来实现2>/dev/null
。(在英语中,这是“将(>
)第二个输出通道(2
,这是标准错误)重定向到/dev/null
(它只是丢弃发送到那里的所有内容)”。
那么,答案是:
$ sudo apt update 2>/dev/null | grep packages | cut -d '.' -f 1
4 packages can be upgraded
Run Code Online (Sandbox Code Playgroud)
旁注:在问题中,您的命令显示为# sudo apt...
. 在#
shell提示符意味着使用该命令时,你很可能以root身份登录。如果您已经是 root,则无需使用sudo
.
有关您要忽略的警告的更多信息(来自man apt
):
SCRIPT USAGE
The apt(8) commandline is designed as a end-user tool and it may change
the output between versions. While it tries to not break backward
compatibility there is no guarantee for it either. All features of
apt(8) are available in apt-cache(8) and apt-get(8) via APT options.
Please prefer using these commands in your scripts.
Run Code Online (Sandbox Code Playgroud)
您可以使用以下命令作为替代方案
sudo apt-get -s upgrade | grep -P "\d\K upgraded"
输出应该是这样的
6 upgraded, 0 newly installed, 0 to remove and 0 not upgraded.
手段-s
是模拟、侦察或试运行
从apt-get
手册页
-s, --simulate, --just-print, --dry-run, --recon, --no-act
No action; perform a simulation of events that would occur based on
the current system state but do not actually change the system.
Locking will be disabled (Debug::NoLocking) so the system state
could change while apt-get is running. Simulations can also be
executed by non-root users which might not have read access to all
apt configuration distorting the simulation. A notice expressing
this warning is also shown by default for non-root users
(APT::Get::Show-User-Simulation-Note). Configuration Item:
APT::Get::Simulate.
Run Code Online (Sandbox Code Playgroud)
这个答案的灵感来自这个博客
归档时间: |
|
查看次数: |
40912 次 |
最近记录: |