Skip to content

Instantly share code, notes, and snippets.

@NinjacksonXV
Last active April 4, 2025 17:53
Show Gist options
  • Save NinjacksonXV/9cf334e159c74cac6cf121b4bbbea7c3 to your computer and use it in GitHub Desktop.
Save NinjacksonXV/9cf334e159c74cac6cf121b4bbbea7c3 to your computer and use it in GitHub Desktop.
Fetches a directory from a Github repository tree URL. I use this to pull individual configuration files when accessing one of my remote machines.
#!/usr/bin/env bash
# Dependencies: gh, jq
# TODO:
# - [ ] Create fallback with bash RegEx to replace jq calls
# - [ ] Create fallback with curl to replace gh calls
bold=$(tput bold)
normal=$(tput sgr0)
FORMAT="${bold}https://github.com/<user>/<repo>/tree/<branch>/<path>${normal}"
FORMAT_REGEX="https://github.com/([^/]+)/([^/]+)/tree/([^/]+)/(.*)"
for dep in "gh" "jq"; do
if ! command -v $dep 2>&1 >/dev/null; then
echo "Command missing: ${bold}$dep${normal}"
dep_missing=1
fi
done
if [ $dep_missing -eq 1 ]; then exit 1; fi
if [ -z "$1" ]; then
echo "Usage: $0 <GitHub directory URL> in format $FORMAT"
exit 1
fi
download() {
URL="$1"
if [[ "$URL" =~ $FORMAT_REGEX ]]; then
USER="${BASH_REMATCH[1]}"
REPO="${BASH_REMATCH[2]}"
BRANCH="${BASH_REMATCH[3]}"
DIR="${BASH_REMATCH[4]}"
else
echo "Invalid URL format. Expected: $FORMAT"
echo "If you're trying to download the entire repository, just ${bold}git clone${normal} it!"
exit 1
fi
mkdir -p "$DIR"
API_URL="repos/$USER/$REPO/contents/$DIR?ref=$BRANCH"
response=$(gh api "$API_URL")
echo "$response" | jq -r '.[] | select(.type=="file") | .download_url + " " + .path' | while read -r url path; do
echo "Downloading $path"
curl -sL "$url" -o "$path"
done
# Recurse into subdirectories
echo "$response" | jq -r '.[] | select(.type=="dir") | .path' | while read -r subdir; do
echo "Downloading $subdir"
download "https://github.com/$USER/$REPO/tree/$BRANCH/$subdir"
done
}
download $1
echo "Download complete."
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment