Skip to content

Instantly share code, notes, and snippets.

@fsgreco
Created August 18, 2022 16:32
Show Gist options
  • Save fsgreco/4295440bdf62df6ad36e8dcf435cbcef to your computer and use it in GitHub Desktop.
Save fsgreco/4295440bdf62df6ad36e8dcf435cbcef to your computer and use it in GitHub Desktop.
Two bash functions that interact with github gist public API. It is made for single file gists. You can retrieve the list of gists for a given user and then download a specific gist.
#!/bin/bash
# MIT © Santiago Greco - fsgreco@hey.com
# This file set two bash functions that interact with github gist public API. It is made for single file gists.
# The first one "gist_list" retrieves a list of public gist from a given username (the only param you need to pass).
# The second one "download_gist" downloads the single gist file (need to have 2 params: username and gits_name)
function check_jq() {
if ! command -v jq &> /dev/null; then echo "Please install 'jq'." && exit 1; fi
}
#e.g. of usage: gist_list fsgreco
function gist_list() {
[ -z "$1" ] && echo 'Please give me the username of the user you want gist from' && exit 1
check_jq
user_name="$1"
curl -sS -H "Accept: application/vnd.github+json" \
"https://api.github.com/users/$user_name/gists" | \
jq 'map( { file: ( .files | keys)[0], description } )'
}
#e.g. of usage: download_gist fsgreco tmux-sessionizer.sh
function download_gist() {
[[ -z "$1" || -z "$2" ]] && echo 'Please give me the username and the name of the gist you want to download' && exit 1
check_jq
user_name="$1"
file_name="$2"
curl -sS -H "Accept: application/vnd.github+json" \
"https://api.github.com/users/$user_name/gists" | \
jq "map( select( (.files | keys)[0] == \"${file_name}\") )" | \
jq ".[].files.\"${file_name}\".raw_url" | \
xargs curl -sS > "$file_name" \
&& echo "$file_name - downloaded"
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment