Skip to content

Instantly share code, notes, and snippets.

@atward
Created Mar 5, 2019
Embed
What would you like to do?
Script to download asset file from tag release using GitHub API v3
#!/usr/bin/env bash
# Script to download asset file from tag release using GitHub API v3.
# See: http://stackoverflow.com/a/35688093/55075
# Check dependencies.
set -e
type curl grep sed tr >&2
# Validate settings.
[ "$GITHUB_API_TOKEN" ] || { echo "Error: Please define GITHUB_API_TOKEN variable." >&2; exit 1; }
[ $# -ne 4 ] && { echo "Usage: $0 [owner] [repo] [tag] [name]"; exit 1; }
[ "$TRACE" ] && set -x
read -r owner repo tag name <<<"$@"
# Define variables.
GH_API="https://api.github.com"
GH_REPO="$GH_API/repos/$owner/$repo"
if [[ "$tag" == "latest" ]]; then
GH_TAGS="$GH_REPO/releases/latest"
else
GH_TAGS="$GH_REPO/releases/tags/$tag"
fi
AUTH="Authorization: token $GITHUB_API_TOKEN"
CURL_ARGS="-LJO#"
# Validate token.
curl -o /dev/null -sH "$AUTH" "$GH_REPO" || { echo "Error: Invalid repo, token or network issue!"; exit 1; }
# Read asset tags.
response=$(curl -sH "$AUTH" "$GH_TAGS")
# Get ID of the asset based on given name.
eval $(echo "$response" | grep -C3 "name.:.\+$name" | grep -w id | tr : = | tr -cd '[[:alnum:]]=')
#id=$(echo "$response" | jq --arg name "$name" '.assets[] | select(.name == $name).id') # If jq is installed, this can be used instead.
[ "$id" ] || { echo "Error: Failed to get asset id, response: $response" | awk 'length($0)<100' >&2; exit 1; }
GH_ASSET="$GH_REPO/releases/assets/$id"
# Download asset file.
echo "Downloading asset..." >&2
curl $CURL_ARGS -H 'Accept: application/octet-stream' "$GH_ASSET?access_token=$GITHUB_API_TOKEN"
echo "$0 done." >&2
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment