如何解决在bash中检查是否安装了RPM软件包的function?

我写了这个函数:

function isInstalled { if [ rpm -q $1 &> /dev/null ]; then echo 'installed'; return 1; else echo 'not installed'; return 0; fi } 

但是有些事情是错的。 它总是返回0.即使包安装。 我想我没有正确地检查返回信号。

 [vagrant@centos-7 ~]$ isInstalled wget2 not installed [vagrant@centos-7 ~]$ isInstalled wget not installed [vagrant@centos-7 ~]$ rpm -q wget wget-1.14-10.el7_0.1.x86_64 

if [ rpm -q ... &> /dev/null ]无效,则使用[ builtin。 如果你没有redirectstderr,你会在错误信息中看到这个:

 if [ rpm -q $1 >/dev/null ]; then 

你执行的每一个命令都有一个退出代码,所以不需要在[ ... ]打包,而且它是无效的语法。

这样写:

 isInstalled() { if rpm -q $1 &> /dev/null; then echo 'installed'; return 1; else echo 'not installed'; return 0; fi } 

你的function应该写成

 isInstalled() { if rpm -q "$1" >/dev/null ; then echo "installed" return 0 else echo "not installed" return 1 fi } 

笔记:

  • 定义一个函数的可移植语法就是这样

     function_name() { … } 
  • 方括号[ ]仅用于特定types的testing ,例如string是否为空。 您不需要它们来检查命令的退出状态。

  • 你的redirect语法是错误的。

  • 在shell编程中,通常返回一个成功的零状态和一个非零状态的失败。 因此,你应该交换你的返回值。

  • 每当引用任何variables时,几乎都应该使用双引号。 否则,您的脚本将会以意外的input(例如参数中的空格字符)中断(可能以安全性妥协的方式)。

 function isInstalled { rpm -q $1 &> /dev/null; if [ $? == 0 ]; then return true; else return false; fi } 

testing: if [ isInstalled wget ]; then echo 'installed'; else echo 'not installed'; fi if [ isInstalled wget ]; then echo 'installed'; else echo 'not installed'; fi