Checking for installed packages and if not found install

42,580

Solution 1

Try the following code :

if ! rpm -qa | grep -qw glibc-static; then
    yum install glibc-static
fi

or shorter :

rpm -qa | grep -qw glibc-static || yum install glibc-static

For debian likes :

dpkg -l | grep -qw package || apt-get install package

For archlinux :

pacman -Qq | grep -qw package || pacman -S package

Solution 2

Based on @GillesQuenot and @Kidbulra answers, here's an example how to loop over multiple packages, and install if missing:

packageList="git gcc python-devel"

for packageName in $packageList; do
  rpm --quiet --query $packageName || sudo yum install -y $packageName
done
Share:
42,580

Related videos on Youtube

amanada.williams
Author by

amanada.williams

Updated on September 26, 2020

Comments

  • amanada.williams
    amanada.williams over 3 years

    I need to check for installed packages and if not installed install them.

    Example for RHEL, CentOS, Fedora:

    rpm -qa | grep glibc-static
    glibc-static-2.12-1.80.el6_3.5.i686
    

    How do I do a check in BASH?

    Do I do something like?

    if [ "$(rpm -qa | grep glibc-static)" != "" ] ; then
    

    And what do I need to use for other distributions? apt-get?

    • Ignacio Vazquez-Abrams
      Ignacio Vazquez-Abrams over 11 years
      Why not just make them required by your packages and have the package manager deal with all that?
    • amanada.williams
      amanada.williams over 11 years
      It's just a simple bash install script to automate some things. :)
  • Gilles Quenot
    Gilles Quenot about 9 years
    Silent + only whole words, not just part of words
  • Adam Burley
    Adam Burley over 6 years
    Hi all, I was using this code in something else and found that this does not differentiate partial matches. in my case (RedHat) I had a package file-libs installed but not file which was what I wanted; when I put rpm -qa | grep -qw file || yum install -y file, then file didn't install. The best solution is not to use grep at all. Just use something like this: rpm --quiet --query file || yum install -y file