A few years ago, I wrote an Ansible role to download the latest version of a file from a Github release. Around the same point, I also wrote a bash script to do the same thing. For some reason, I never released either of them (or if I did, I can’t find them), so here’s the Bash one, as I needed to reuse it today :)
#!/bin/bash
AGENT=""
TRY_WGET=1
TRY_CURL=1
if [ "$TRY_WGET" == "1" ] && command -v wget >/dev/null 2>&1
then
AGENT=wget
elif [ "$TRY_CURL" == "1" ] && command -v curl >/dev/null 2>&1
then
AGENT=curl
fi
if [ -z "$AGENT" ]
then
echo "Error: No HTTP agent (curl and wget tested)" >&2
exit 1
fi
DEBUG() {
echo "$@" >&2
}
GET() {
URL="$1"
TARGET="${2:-}"
if [ "$AGENT" == "curl" ]
then
if [ -z "$TARGET" ]
then
DEBUG curl --silent "$URL"
curl --silent "$URL"
elif [ "$TARGET" == "ORIGIN" ]
then
DEBUG curl --silent -LO "$URL"
curl --silent -LO "$URL"
else
DEBUG curl --output "$TARGET" --silent "$URL"
curl --output "$TARGET" --silent "$URL"
fi
else
if [ -z "$TARGET" ]
then
DEBUG wget -qO- "$URL"
wget -qO- "$URL"
elif [ "$TARGET" == "ORIGIN" ]
then
DEBUG wget -q "$URL"
wget -q "$URL"
else
DEBUG wget -q -O "$TARGET" "$URL"
wget -q -O "$TARGET" "$URL"
fi
fi
}
REPO="${1:-}"
ASSET="${2:-}"
VERSION="${3:-latest}"
[ "$VERSION" != "latest" ] && VERSION="tags/$3"
RELEASE_JSON=$(GET "https://api.github.com/repos/$REPO/releases/$VERSION")
ASSET_URL=$(echo "$RELEASE_JSON" | grep -oP "(?<=browser_download_url\": \")[^\"]*${ASSET}" | head -n 1)
if [ -n "$ASSET_URL" ]
then
GET "$ASSET_URL" "${OUTPUT:-ORIGIN}"
else
echo "Asset not found" >&2
exit 2
fi
This is also available as a gist on github.
Featured image is “Yes!” by “storebukkebruse” on Flickr and is released under a CC-BY license.