How to check for package inside shell script

Today, I want to briefly describe a simple way to check for specific package inside shell script.

The following function uses dpkg-query utility to examine if specified package is installed. Then, in case of failure, it examines if package is available in locally configured repositories using apt-cache command.

# check for specific package
# Return values:
#  0 - package is installed
#  1 - package is not installed, it is available in package repository
#  2 - package is not installed, it is not available in package repository
check_for_package(){
  if dpkg-query -s "$1" 1>/dev/null 2>&1; then
    return 0   # package is installed
  else
    if apt-cache show "$1" 1>/dev/null 2>&1; then
      return 1 # package is not installed, it is available in package repository
    else
      return 2 # package is not installed, it is not available in package repository
    fi
  fi
}

Regular shell script to illustrate the usage.

#!/bin/sh
# check for specific package
# Return values:
#  0 - package is installed
#  1 - package is not installed, it is available in package repository
#  2 - package is not installed, it is not available in package repository
check_for_package(){
  if dpkg-query -s "${1}" 1>/dev/null 2>&1; then
    return 0   # package is installed
  else
    if apt-cache show "$1" 1>/dev/null 2>&1; then
      return 1 # package is not installed, it is available in package repository 
    else
      return 2 # package is not installed, it is not available in package repository
    fi
  fi
}

# example
packages="bash bashdb mc openssl-dev type"

for package in $packages; do
  if check_for_package "$package"; then
    printf "%-20s - %s\n" "$package" "package is installed"
  else
    if test "$?" -eq 1; then
      printf "%-20s - %s\n" "$package" "package is not installed, it is available in package repository"
    else
      printf "%-20s - %s\n" "$package" "package is not installed, it is not available in package repository"
    fi
  fi
done

Sample output.

bash                 - package is installed
bashdb               - package is not installed, it is available in package repository
mc                   - package is installed
openssl-dev          - package is not installed, it is not available in package repository
type                 - package is not installed, it is not available in package repository

Additional notes

I cannot use simple &>/dev/null redirection as dash command interpreter does not support it, so I need take advantage of the longer 1>/dev/null 2>&1 version to get rid of the whole (standard and error) output inside shell functions.

Milosz Galazka's Picture

About Milosz Galazka

Milosz is a Linux Foundation Certified Engineer working for a successful Polish company as a system administrator and a long time supporter of Free Software Foundation and Debian operating system.

Gdansk, Poland https://sleeplessbeastie.eu