apt-get download with version constraint

I need to use apt-get download to fetch a specific version of a .deb file, but not necessarily the exact version. .deb dependencies are allowed to use expressions such as >=0.3.0 and I would like apt-get download to fetch the same version as the one that would be downloaded using such dependency.

Summing it up, what I want to work is this:

$ apt-get download package='>=0.3.0'

Any idea how I could get that functionality?


Solution 1:

You could do this by first finding out which version is the newest version that is also greater than or equal to your desired minimum version. Then, you download exactly that version using apt-get download. Here's a script that does this (it's a bit ugly, but you get the idea):

#!/bin/bash

if [ $# -lt 2 ]; then
    echo "Usage: $0 <packagename> <minimum version>"
    exit 1
fi

pkgname="$1"
minversion="$2"

V="0"

for version in `apt-cache madison $pkgname | awk -F'|' '{print $2}'`; do
    echo "Considering $version"
    if dpkg --compare-versions $version ge $minversion; then
        echo "- Version is at least $minversion"
        if dpkg --compare-versions $version gt $V; then
            echo "- This is the newest version so far"
            V=$version
        else
            echo "- We already have a newer version"
        fi
    else
        echo "- This is older than $minversion"
    fi
done

if [ "$V" = "0" ]; then
    echo "There is no version greater than or equal to $minversion"
    exit 1
fi

echo "Selected version: $V"

echo "Downloading"
apt-get download $pkgname=$V
echo "Done"

You'd have to add error checking in case the package doesn't exist, etc. but this contains the core solution. Also, I've assumed here that you want the newest available package that is at least a certain version. If you would instead like the oldest available package that is at least a certain version, you have to adjust the script to stop searching once it's found something that is at least your desired version.