Skip to content

Instantly share code, notes, and snippets.

@sarvsav
Created March 5, 2024 20:12
Show Gist options
  • Save sarvsav/f68e4128e02b0221096afac705cf3ff0 to your computer and use it in GitHub Desktop.
Save sarvsav/f68e4128e02b0221096afac705cf3ff0 to your computer and use it in GitHub Desktop.
Download the latest release from the github repo
#!/bin/bash
# Check if jq is installed
if ! command -v jq &> /dev/null; then
echo "jq is required but it's not installed. Please install jq first."
exit 1
fi
# Check if curl is installed
if ! command -v curl &> /dev/null; then
echo "curl is required but it's not installed. Please install curl first."
exit 1
fi
# Check if repository and owner names are provided
if [ -z "$1" ]; then
echo "Usage: $0 <owner>/<repository>"
exit 1
fi
repo_owner_repo=$1
# Get the download URL of the latest release
download_url=$(curl -sL "https://api.github.com/repos/$repo_owner_repo/releases/latest" | \
jq -r '.assets[].browser_download_url' | \
grep -i "$(uname -s)" | \
grep -i amd)
# Check if a download URL is found
if [ -z "$download_url" ]; then
echo "Failed to retrieve the download URL of the latest release."
exit 1
fi
# Determine the file name from the download URL
file_name=$(basename "$download_url")
# Check if $HOME/bin exists, if not, create it
bin_dir="$HOME/bin"
if [ ! -d "$bin_dir" ]; then
mkdir -p "$bin_dir"
fi
# Check if the file already exists
if [ -f "$bin_dir/$file_name" ]; then
read -p "File $file_name already exists. Do you want to replace it? (y/n): " replace_file
if [ "$replace_file" != "y" ]; then
echo "Operation canceled by user."
exit 0
fi
fi
# Download the latest release
echo "Downloading the latest release from: $download_url"
curl -LO "$download_url"
# Move the downloaded file to $HOME/bin
mv "$file_name" "$bin_dir/"
# Set executable permissions for the file
chmod +x "$bin_dir/$file_name"
# Calculate checksums of the downloaded file
md5sum=$(md5sum "$bin_dir/$file_name" | awk '{print $1}')
sha1sum=$(sha1sum "$bin_dir/$file_name" | awk '{print $1}')
sha256sum=$(sha256sum "$bin_dir/$file_name" | awk '{print $1}')
# Print checksums in tabular format
printf "\nChecksums:\n"
printf "+------------+----------------------------------+\n"
printf "| Algorithm | Checksum |\n"
printf "+------------+----------------------------------+\n"
printf "| MD5 | %-32s |\n" "$md5sum"
printf "| SHA1 | %-40s |\n" "$sha1sum"
printf "| SHA256 | %-64s |\n" "$sha256sum"
printf "+------------+----------------------------------+\n"
# Run the version command
"$bin_dir/$file_name" version
#### How to run
## $ ./download_latest_release.sh bazelbuild/bazelisk
##
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment