How do I extract the package version from debian/changelog?

Solution 1:

If you have version 1.17.0 or later, you can use

dpkg-parsechangelog --show-field Version

No need to process the output further then. This version is currently (February 2014) available in Debian Testing.

Solution 2:

There are numerous ways to do this.

dpkg-parsechangelog | sed -n 's/^Version: //p'

or alternatively:

dpkg-parsechangelog | grep Version: | cut -d' ' -f2-

Solution 3:

dpkg-parsechangelog works, and the earlier answer piping the output through sed/grep should be entirely robust. If you want to know precise details of the format of dpkg-parsechangelog output, and most other debian-style control files, see RFC 822. It is never ok for a deb package version to contain a newline, space, or any other special or control characters (see man deb-version), so the "Version: blah" line in the output will always be present, and it will always be a single line on its own.

However, dpkg-parsechangelog is a very heavy program to run just to get the current version number from a changelog. It has to run Perl and load an impressively large number of libraries in order to give you a result, most of which you won't use. On slower platforms, or with slow file storage media, or when you need to do this version parsing lots of times, it will prove quite painfully slow. Instead, just use whatever is inside the first set of parentheses on the first line:

head -1 debian/changelog | awk -F'[()]' '{print $2}'

That will get you the correct current package version with any valid changelog file using the standard format (and nonstandard debian/changelog formats are, for all practical general purposes, never used).