Skip to content

Instantly share code, notes, and snippets.

@sgleske-ias
Last active July 18, 2018 06:36
Show Gist options
  • Save sgleske-ias/515a465f067cb1cdbbe8d82fe8d71e70 to your computer and use it in GitHub Desktop.
Save sgleske-ias/515a465f067cb1cdbbe8d82fe8d71e70 to your computer and use it in GitHub Desktop.
Run it: bash -x download_and_verify.sh
#!/bin/bash
#Mon Feb 26 13:01:50 PST 2018
#Darwin 16.7.0 x86_64
#GNU bash, version 3.2.57(1)-release (x86_64-apple-darwin16)
#Download and verify a file's sha256sum
#Retry three times and then fail.
#Should check the sha256sum of the downloaded file before attempting to download.
#exit 0 on success else exit nonzero
#Usage:
# download_and_verify /path/to/local/file <sha256 hash> <remote download location>
function download_and_verify() {
if [ ! $# -eq 3 ]; then
echo "ERROR: malformed function call: $0 $*" >&2
echo 'EXPECTED 3 args: download_and_verify <local file> <sha256 hash> <remote download location>'
return 1
fi
local lfile="${1}"
local shasum="${2}"
local rfile="${3}"
local retries=3
local verify_command=()
if type -P sha256sum &> /dev/null; then
verify_command+=( 'sha256sum' '-c' '-' )
elif type -P shasum &> /dev/null; then
verify_command+=( 'shasum' '-a' '256' '-c' '-')
else
echo 'ERROR: could not determine sha256sum command' >&2
return 1
fi
if "${verify_command[@]}" <<< "${shasum} ${lfile}"; then
#file exists and matches checksum so return success
return 0
fi
local current_try=0
while [[ current_try -lt retries ]]; do
if curl -fLo "${lfile}" "${rfile}"; then
#download success
break
fi
(( current_try++ ))
done
#return status code based on shasum
"${verify_command[@]}" <<< "${shasum} ${lfile}"
}
download_and_verify ~/Downloads/dumb-init \
057ecd4ac1d3c3be31f82fc0848bf77b1326a975b4f8423fe31607205a0fe945 \
https://github.com/Yelp/dumb-init/releases/download/v1.2.1/dumb-init_1.2.1_amd64
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment