Skip to content

Instantly share code, notes, and snippets.

@craig-m-unsw
Created September 22, 2023 00:34
Show Gist options
  • Select an option

  • Save craig-m-unsw/93a7260aa4bf4ebabbbf17de176a2a41 to your computer and use it in GitHub Desktop.

Select an option

Save craig-m-unsw/93a7260aa4bf4ebabbbf17de176a2a41 to your computer and use it in GitHub Desktop.
# Gets a list of files and/or directories to build a SHA-256 from their contents.
# Returns the SHA-256 hash if succeeded, otherwise an empty string.
sha256sum_from_files() {
local files_in=${@:-}
local files=""
local shasum=""
# Process the input files:
# - discard the files/directories that don't exist.
# - find the files if it is a directory
for f in $files_in; do
if [ -d "$f" ]; then
files+=" $(find $f -type f)"
elif [ -f "$f" ]; then
files+=" $f"
fi
done
# Return in case there is none input files.
[ -n "$files" ] || return 0
# Alphabetically sorting the files.
files="$(echo $files | tr ' ' '\n' | LC_ALL=C sort -u)"
# Concate the files and calculate a hash.
shasum="$(cat $files | sha256sum -b)" || true
if [ -n "$shasum" ];then
# Return only the SHA field.
echo $(awk '{ print $1 }' <<< $shasum)
fi
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment