Skip to content

Instantly share code, notes, and snippets.

@Tugzrida
Last active December 11, 2020 06:44
Show Gist options
  • Save Tugzrida/325fa2175f77064858006dca502ad443 to your computer and use it in GitHub Desktop.
Save Tugzrida/325fa2175f77064858006dca502ad443 to your computer and use it in GitHub Desktop.
Simple bash hash verification utility
#!/bin/bash
# hashchecker Created by Tugzrida(https://gist.github.com/Tugzrida)
# A simple utility that accepts a file path and expected md5, sha1 or
# sha256 hash, then verifies the file matches the expected hash.
# Hash length assumptions:
# md5 - 32 chars
# sha1 - 40 chars
# sha256 - 64 chars
file_to_verify="$1"
expected_hash="$2"
length=${#expected_hash}
case "$length" in
32)
md5=true
;;
40)
sha1=true
;;
64)
sha256=true
;;
128)
sha512=true
;;
*)
echo "Usage: $(basename $0) file_to_verify expected_hash"
exit 1
;;
esac
function abspath()
{
case "${1}" in
[./]*)
echo "$(cd ${1%/*}; pwd)/${1##*/}"
;;
*)
echo "${PWD}/${1}"
;;
esac
}
echo "Checking hash for $(abspath $file_to_verify)"
if [ $md5 ]; then
echo "Presuming md5 hash. Calculating..."
command -v md5sum >/dev/null && calculated_hash=$(md5sum "$file_to_verify" | awk '{print $1}') || calculated_hash=$(md5 "$file_to_verify" | awk '{print $NF}')
fi
if [ $sha1 ]; then
echo "Presuming sha1 hash. Calculating..."
calculated_hash=$(shasum -a 1 "$file_to_verify" | awk '{print $1}')
fi
if [ $sha256 ]; then
echo "Presuming sha256 hash. Calculating..."
calculated_hash=$(shasum -a 256 "$file_to_verify" | awk '{print $1}')
fi
if [ $sha512 ]; then
echo "Presuming sha512 hash. Calculating..."
calculated_hash=$(shasum -a 512 "$file_to_verify" | awk '{print $1}')
fi
echo "Provided hash: $expected_hash"
echo "Calculated hash: $calculated_hash"
if [ "$calculated_hash" == "$expected_hash" ]; then
printf "\e[92mHashes match\e[39m\n"
exit 0
fi
printf "\e[91mHashes don't match!\e[39m\n"
exit 1
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment