Skip to content

Instantly share code, notes, and snippets.

@hi-ogawa
Last active December 26, 2022 07:46
Show Gist options
  • Save hi-ogawa/1e0b1a147e883aad41f97c68246f3c33 to your computer and use it in GitHub Desktop.
Save hi-ogawa/1e0b1a147e883aad41f97c68246f3c33 to your computer and use it in GitHub Desktop.
download shell script from gist and install it locally
#!/bin/bash
set -eu -o pipefail
#
# something similar to https://github.com/marcosnils/bin but for simple shell scripts on gist
#
# usage:
# bash bin-gist.sh https://gist.github.com/hi-ogawa/1e0b1a147e883aad41f97c68246f3c33 bin-gist.sh
# bash bin-gist.sh https://gist.github.com/hi-ogawa/bca49e90241f7808127a430f986d33ea passphrase.sh
#
# one-liner for self installation:
# curl -sSfL https://gist.githubusercontent.com/hi-ogawa/1e0b1a147e883aad41f97c68246f3c33/raw/f7baad0a365c6fb2e42fd7ef29b15fe393b7b952/bin-gist.sh | bash -s -- https://gist.github.com/hi-ogawa/1e0b1a147e883aad41f97c68246f3c33 bin-gist.sh
#
# parameters
url="$1"
filename="$2"
# gist id
gist_id="${url##*/}"
# tmp file
gist_json="$(mktemp --suffix=.gist.json)"
trap 'rm -rf -- "$gist_json"' EXIT
# fetch github api
echo ":: fetching gist https://api.github.com/gists/$gist_id"
curl -sfL "https://api.github.com/gists/$gist_id" > "$gist_json"
# validate content
if ! jq --exit-status --arg filename "$filename" '.files[$filename]' < "$gist_json" >/dev/null 2>&1; then
echo ":: [ERROR] file not found"
exit 1
fi
if ! jq --exit-status --arg filename "$filename" '.files[$filename].truncated | not' < "$gist_json" >/dev/null 2>&1; then
echo ":: [ERROR] file is too big"
exit 1
fi
# write to $HOME/.local/bin
dst_path="$HOME/.local/bin/$filename"
echo ":: writing to $dst_path"
jq --exit-status -r --arg filename "$filename" '.files[$filename].content' < "$gist_json" > "$dst_path"
# make it executable
chmod +x "$dst_path"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment