How to check from bash if package exists in Debian

(the below is from Ubuntu, but the same technique obviously works on Debian as well)

$ apt-cache show screen
Package: screen
Priority: optional
Section: misc
Installed-Size: 950
Maintainer: Ubuntu Developers <[email protected]>
Original-Maintainer: Axel Beckert <[email protected]>
Architecture: amd64
Version: 4.1.0~20120320gitdb59704-9
Depends: libc6 (>= 2.15), libpam0g (>= 0.99.7.1), libtinfo5
Suggests: iselect (>= 1.4.0-1) | screenie | byobu
Filename: pool/main/s/screen/screen_4.1.0~20120320gitdb59704-9_amd64.deb
Size: 645730
...

If the package exists, information will be displayed. If not, you'll see something like:

$ apt-cache show foobar
N: Unable to locate package foobar
E: No packages found

Additionally, the exit code of apt-cache will be non-zero if no matching packages are found.

Additional note: If you're using apt-cache show package where package is a virtual one (one that doesn't exist, but is, for example, referenced by other packages), you'll get:

N: Can't select versions from package 'package' as it is purely virtual
N: No packages found

The exit code of this is zero (which is a bit misleading in my opinion.)


I would use dpkg -l mysql-server &> /dev/null && echo "mysql-server is installed".

It will check if the mysql-server package is installed and if so, it prints this fact to the screen. A more sophisticated solution would be, in bash (untested):

function package_exists() {
    return dpkg -l "$1" &> /dev/null
}

So one can do in a script:

if ! package_exists mysql-server ; then
    echo ”Please install mysql-server!"
fi

Tags:

Bash

Deb

Apt