60

At our university we can get almost any ubuntu package installed we want, but we are not superusers ourselves (we need to request packages being installed).

With some libraries it is not always easy to know whether the package is already installed or not. Is there a simple way/command to check this?

Radu Rădeanu
  • 174,089
  • 51
  • 332
  • 407
Peter Smit
  • 7,707

9 Answers9

62
apt-cache policy <package name>
Oli
  • 299,380
18

I always just use this from the command line:

dpkg -l | grep mysql

so the above asks dpkg to list all the installed packages and then I grep for only those that have mysql in the name.

Rick
  • 3,727
7

One more variant, using aptitude this time:

aptitude show <package>

Tab completion works here as well.

6

dpkg-query --showformat='${db:Status-Status}'

This produces a small output string which is unlikely to change and is easy to compare deterministically without grep:

pkg=hello
status="$(dpkg-query -W --showformat='${db:Status-Status}' "$pkg" 2>&1)"
if [ ! $? = 0 ] || [ ! "$status" = installed ]; then
  sudo apt install $pkg
fi

The $? = 0 check is needed because if you've never installed a package before, and after you remove certain packages such as hello, dpkg-query exits with status 1 and outputs to stderr:

dpkg-query: no packages found matching hello

instead of outputting not-installed. The 2>&1 captures that error message too when it comes preventing it from going to the terminal.

For multiple packages:

pkgs='hello certbot'
install=false
for pkg in $pkgs; do
  status="$(dpkg-query -W --showformat='${db:Status-Status}' "$pkg" 2>&1)"
  if [ ! $? = 0 ] || [ ! "$status" = installed ]; then
    install=true
    break
  fi
done
if "$install"; then
  sudo apt install $pkgs
fi

The possible statuses are documented in man dpkg-query as:

   n = Not-installed
   c = Config-files
   H = Half-installed
   U = Unpacked
   F = Half-configured
   W = Triggers-awaiting
   t = Triggers-pending
   i = Installed

The single letter versions are obtainable with db:Status-Abbrev, but they come together with the action and error status, so you get 3 characters and would need to cut it.

So I think it is reliable enough to rely on the uncapitalized statuses (Config-files vs config-files) not changing instead.

dpkg -s exit status

This unfortunately doesn't do what most users want:

pkgs='qemu-user pandoc'
if ! dpkg -s $pkgs >/dev/null 2>&1; then
  sudo apt-get install $pkgs
fi

because for some packages, e.g. certbot, doing:

sudo apt install certbot
sudo apt remove certbot

leaves certbot in state config-files, which means that config files were left in the machine. And in that state, dpkg -s still returns 0, because the package metadata is still kept around so that those config files can be handled more nicely.

To actually make dpkg -s return 1 as desired, --purge would be needed:

sudo apt remove --purge certbot

which actually moves it into not-installed/dpkg-query: no packages found matching.

Note that only certain packages leave config files behind. A simpler package like hello goes directly from installed to not-installed without --purge.

Tested on Ubuntu 20.10.

Python apt package

There is a pre-installed Python 3 package called apt in Ubuntu 18.04 which exposes an Python apt interface!

A script that checks if a package is installed and installs it if not can be seen at: https://stackoverflow.com/questions/17537390/how-to-install-a-package-using-the-python-apt-api/17538002#17538002

Here is a copy for reference:

#!/usr/bin/env python
# aptinstall.py

import apt import sys

pkg_name = "libjs-yui-doc"

cache = apt.cache.Cache() cache.update() cache.open()

pkg = cache[pkg_name] if pkg.is_installed: print "{pkg_name} already installed".format(pkg_name=pkg_name) else: pkg.mark_install()

try:
    cache.commit()
except Exception, arg:
    print &gt;&gt; sys.stderr, &quot;Sorry, package installation failed [{err}]&quot;.format(err=str(arg))

Check if an executable is in PATH instead

See: https://stackoverflow.com/questions/592620/how-can-i-check-if-a-program-exists-from-a-bash-script/22589429#22589429

See also

6

You can use dselect. It provides non-su read-only access.

Also, dpkg -s <package name> provides a lot of details related to a package. Eg"

userme:~$ dpkg-query -s sl
Package: sl
Status: unknown ok not-installed
Priority: optional
Section: games
Pablo Bianchi
  • 17,371
Abhinav
  • 239
5

You may use dpkg-query -s <package> 2>/dev/null | grep -q ^"Status: install ok installed"$ in scripts, since it returns exit code 1, if the <package> is not installed, and 0 if the <package> is installed.

jarno
  • 6,175
2

Simpler solution:

There is now an apt list command that lists installed packages. You can also search for a specific package with

apt list <package>

See man apt for more information.

0

You need to check the status printed by dpkg -l, example :

$ dpkg -l firefox-esr vim winff
Desired=Unknown/Install/Remove/Purge/Hold
| Status=Not/Inst/Conf-files/Unpacked/halF-conf/Half-inst/trig-aWait/Trig-pend
|/ Err?=(none)/Reinst-required (Status,Err: uppercase=bad)
||/ Name                                 Version                 Architecture            Description
+++-====================================-=======================-=======================-=============================================================================
hi  firefox-esr                          52.9.0esr+build2-0ubunt amd64                   Safe and easy web browser from Mozilla
ii  vim                                  2:8.1.1198-0york0~14.04 amd64                   Vi IMproved - enhanced vi editor
rc  winff                                1.5.3-3                 all                     graphical video and audio batch converter using ffmpeg or avconv

Here both vim and firefox-esr are installed, therefore you can type :

$ dpkg -l firefox-esr | grep -q ^.i && echo This package is installed. || echo This package is NOT installed.
This package is installed.
$ dpkg -l vim | grep -q ^.i && echo This package is installed. || echo This package is NOT installed.
This package is installed.
$ dpkg -l winff | grep -q ^.i && echo This package is installed. || echo This package is NOT installed.
This package is NOT installed.
SebMa
  • 2,927
  • 5
  • 35
  • 47
-1

Example to use specific value as var in shell scripts (eg test.sh)

#!/bin/sh
PACKAGE="${1}"
INSTALLED=$(dpkg -l | grep ${PACKAGE} >/dev/null && echo "yes" || echo "no")

echo "${PACKAGE} is installed ... ${INSTALLED}"

Make it executable and go start with:

test.sh openssh-server

Or do whatever you want with in your scripts

wjandrea
  • 14,504