Search code examples
bashmacosterminalzshsha

How to check SHA-256 checksum on files?


I know that you can use shasum -a 256 filename to create a SHA-256 checksum for a file, but how can one automate the check if known SHA-256 matches a file on a mac?

Since the Mac shell is zsh by default, but our CI runner uses bash, I want to know both versions (for local testing and for the ci).


Solution

  • I figured it out!

    Using the awk '{ print $1 }', you can omit the filename printed by shasum. This way you can write an easy if statement to check if the SHA checksums match.

    zsh version

    sha=$( shasum -a 256 filename | awk '{ print $1 }')
    if [[ $sha == "known checksum" ]] {
      echo "sha matches"
    } else {
      echo $sha "does not match the required: known checksum"
    }
    

    bash version

    sha=$( shasum -a 256 filename | awk '{ print $1 }')
    if [[ $sha == "known checksum" ]]
    then
      echo "sha matches"
    else
      echo $sha "does not match the required: known checksum"
    fi