How can I tell whether a package is installed via yum in a bash script?

I found the following on a semi-related StackOverflow question; the answer I needed didn't actually quite answer the question there (and was not selected as the correct answer) so I figured I'd post it here for others to find easier.

yum list installed PACKAGE_NAME

This command returns some human-readable output, but more importantly returns an exit status code; 0 indicates the package is installed, 1 indicates the package is not installed (does not check whether the package is valid, so yum list installed herpderp-beepbopboop will return a "1" just as yum list installed traceroute will if you don't have traceroute installed). You can subsequently check "$?" for this exit code.

Since the output is somewhat counter-intuitive, I used @Chris Downs' "condensed" version below in a wrapper function to make the output more "logical" (i.e. 1=installed 0=not installed):

function isinstalled {
  if yum list installed "$@" >/dev/null 2>&1; then
    true
  else
    false
  fi
}

usage would be

if isinstalled $package; then echo "installed"; else echo "not installed"; fi

EDIT:

Replaced return statements with calls to true and false which help make the function more readable/intuitive, while returning the values bash expects (i.e. 0 for true, 1 for false).

If you're just checking for one package in your script, you may just be better off testing yum list installed directly, but (IMHO) the function makes it easier to understand what's going on, and its syntax is much easier to remember than yum with all the redirects to supress its output.


Not exactly fulfilling the precondition of the question "via yum" but faster than "yum -q list" is:

rpm -q <package_name>

which returns the exact name of the possibly installed version as well as the error code "0" if installed and "1" if not.


Simpler oneliner:

yum -q list installed packageX &>/dev/null && echo "Installed" || echo "Not installed"