How to verify package version in shell script

There are circumstances when you want to ensure particular package version during setup process. I will show you a simple method to verify package version that is suitable for sourcing into a shell script.

You can quickly print package version using dpkg-query utility.

$ dpkg-query -W -f='${Version}\n' apache2
2.4.10-10+deb8u7

This command can be smoothly used in shell script to perform different actions depending on package version or its presence in the system.

#!/bin/sh
# perform different actions depending on package status

# required package version
required_package="apache2-utils"
required_version="2.4.10-10+deb8u6"

# local package version
local_version=$(/usr/bin/dpkg-query -W -f="\${Version}\n" $required_package 2>/dev/null)

# verify package version
case $local_version in
  "")
     echo "Package \"$required_package\" is not installed"
     exit 1
     ;;
  $required_version)
     echo "Package \"$required_package\" is installed, version constraint is met (\"$required_version\")"
     exit 0
     ;;
  *)
     most_recent_version=$(printf "${required_version}\n${local_version}\n" | sort -h | tail -1)
     if [ "$local_version" == "$most_recent_version" ]; then
         echo "Package \"$required_package\" is installed, version constraint is met (\"$local_version\" is newer than \"$required_version\")"
         exit 0
     else
         echo "Package \"$required_package\" is installed, version constraint is not met (\"$local_version\" is older than \"$required_version\")"
         exit 1
     fi
     ;;
esac
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. He is also open for new opportunities and challenges.

Gdansk, Poland https://sleeplessbeastie.eu