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

  • I am trying to write a script that installs packages, but if it fails at any point later in the script rolls back whatever it installed. Of course if the user has already previously installed a package I don't want to uninstall it out from under them. How can my script tell whether a package has been previously installed via yum?

  • Doktor J

    Doktor J Correct answer

    7 years ago

    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 "[email protected]" >/dev/null 2>&1; then

    usage would be

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


    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.

    You don't need to manually check the value of `$?`, just wrap the command in a conditional: `if yum list installed "$package" >/dev/null 2>&1; then [...]`

    I think your echo statements are reversed, no? `isInstalled` returns 1 if the package is installed; but 1 is evaluated to false in bash so "not installed" is echoed.

    @FGreg good call... I've replaced the `return` statements with calls to `true` and `false`, so the function is easily readable yet returns the output bash expects.

    OMG it's the 21st century, can't they have a proper option to tell if a package is installed so I don't have write functions or one liners!?

License under CC-BY-SA with attribution

Content dated before 6/26/2020 9:53 AM