Reliably check if a package is installed or not

Essentially you only need to replace the if condition with

if dpkg --get-selections | grep -q "^$pkg[[:space:]]*install$" >/dev/null; then

It is not possible to use dpkg-query, because it returns true also for packages removed but not purged.

Also I suggest to check the exit code of apt-get before giving the successful message:

if apt-get -qq install $pkg; then
    echo "Successfully installed $pkg"
else
    echo "Error installing $pkg"
fi

You can test it by dpkg-query:

if dpkg-query -W -f'${Status}' "$pkg" 2>/dev/null | grep -q "ok installed"; then

Note that * and ? are wildcards, if they appear in $pkg. I guess dpkg-query may print "reinst-required installed" instead of "ok installed", if package is broken and needs to be reinstalled by command apt-get install --reinstall which can be used to install new packages as well.

Tags:

Scripts