Two sheets of card, the first illustrated with an individual next to a school bus, and the word "Release" and the second with the same individual and two others, around the word "Joy" and hearts

Getting an asset from a Github Release in Bash

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.

JonTheNiceGuy

He/Him. Husband and father. Linux advocating geek. Co-Host on the AdminAdmin Podcast, occasional conference speaker.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Your post must include a link to this post.

How does this work?
Write a response on your own website and include a link to this post. Then submit your response’s URL here. Your response may appear here after moderation. To update or remove it, edit or delete your original post and submit the same URL again. Learn more about Webmentions.