以静默方式检查 bash 脚本中是否存在 rpm

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8084142/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 21:11:12  来源:igfitidea点击:

Check if rpm exists in bash script silently

bashrpm

提问by Danny

I'm trying to do a quick check to see if an rpm is installed in a bash script using an if statement. But I want to do it silently. Currently, when I run the script, and the rpm does exist, it outputs the output of rpm to the screen which I dont want.

我正在尝试使用 if 语句快速检查 rpm 是否安装在 bash 脚本中。但我想默默地做。目前,当我运行脚本并且 rpm 确实存在时,它会将 rpm 的输出输出到我不想要的屏幕上。

if rpm -qa | grep glib; then
    do something
fi

Maybe there is an option to rpm that I am missing? or if I just need to change my statement?

也许有我缺少的 rpm 选项?或者如果我只需要更改我的陈述?

THanks

谢谢

采纳答案by vromanov

1) You can add -q switch to grep

1) 您可以将 -q 开关添加到 grep

if rpm -qa | grep -q glib; then
  do something
fi

2) You can redirect stout and/or stderr output to /dev/null

2) 您可以将 Stout 和/或 stderr 输出重定向到 /dev/null

if rpm -qa | grep glib  2>&1 > /dev/null; then
  do something
fi

回答by ztank1013

There is the interesting --quietoption available for the rpmcommand. Man page says:

--quietrpm命令有一个有趣的选项。手册页说:

   --quiet
          Print  as little as possible - normally only error messages will
          be displayed.

So probably you may like to use this one:

所以可能你可能喜欢使用这个:

if rpm -q --quiet glib ; then 
  do something 
fi

This way should be faster because it doesn't have to wait a -qa(query all) rpm packages installed but just queries the target rpm package. Of course you have to know the correct name of the package you want to test if is installed or not.

这种方式应该更快,因为它不必等待-qa(查询所有)安装的 rpm 包,而只是查询目标 rpm 包。当然,您必须知道要测试的软件包是否已安装的正确名称。

Note: using RPM version 4.9.1.2 on fedora 15

注意:在 fedora 15 上使用 RPM 版本 4.9.1.2

回答by user2153517

You need only -q option actually:

您实际上只需要 -q 选项:

$ rpm -q zabbix-agent

package zabbix-agent is not installed

$ rpm -q curl

curl-7.24.0-5.25.amzn1.x86_64

It will look like:

它看起来像:

$ if rpm -q zabbix-agent > /dev/null; then echo "Package zabbix-agent is already installed."; fi

Package zabbix-agent is already installed.

回答by JRFerguson

You could do:

你可以这样做:

[ -z "$(rpm -qa|grep glib)" ] && echo none || echo present

...or, if you prefer:

...或者,如果您愿意:

if [ $(rpm -qa|grep -c glib) -gt 0 ]; then
    echo present
else
    echo none
fi

回答by ata

You could test if the command returns a string, the command substitution will capture the output:

您可以测试命令是否返回字符串,命令替换将捕获输出:

[[ "$(rpm -qa | grep glib)" ]] && do something