Skip to content

Instantly share code, notes, and snippets.

@stuaxo
Last active May 15, 2023 22:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save stuaxo/2e110aaa42050490ad3fd73cfbedf76a to your computer and use it in GitHub Desktop.
Save stuaxo/2e110aaa42050490ad3fd73cfbedf76a to your computer and use it in GitHub Desktop.
Download all files in a github gist to the current directory
#!/bin/bash
#
# Download all the files in a GitHub Gist
#
# Example usage:
# $ download-gist.sh https://gist.github.com/stuaxo/2e110aaa42050490ad3fd73cfbedf76a
#
# By default, files are not overwritten. The -f option overrides this behavior:
# $ download-gist.sh -f https://gist.github.com/stuaxo/2e110aaa42050490ad3fd73cfbedf76a
#
force_download=false
if [ "$#" -eq 2 ] && [ "$2" = "-f" ]; then
force_download=true
elif [ "$#" -ne 1 ]; then
echo "Usage: $0 [-f] <gist_url>"
exit 1
fi
gist_url="$1"
gist_id=$(basename "$gist_url")
api_url="https://api.github.com/gists/$gist_id"
response=$(curl -s "$api_url")
if [[ $response == *"Not Found"* ]]; then
echo "Gist not found!"
exit 1
fi
should_download=true
files=$(echo "$response" | grep -Eo '"filename":\s*"[^"]+"' | cut -d'"' -f4 | sed -e 's/^[[:space:]]*//')
if [ "$force_download" = false ]; then
for file in $files; do
if [ -f "$file" ]; then
echo "Skipping $file (already exists)"
should_download=false
fi
done
fi
if [ "$should_download" = true ]; then
for file in $files; do
file_url=$(echo "$response" | jq -r --arg file "$file" '.files[$file].raw_url')
echo "Downloading $file..."
# Download the file and check for non-200 status code
download_status_code=$(curl -s -L -w "%{http_code}" -o "$file" "$file_url")
if [ "$download_status_code" != "200" ]; then
echo "Failed to download $file (HTTP Status Code: $download_status_code)"
rm "$file" # Remove the empty file
fi
done
fi
echo "Download complete!"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment