How to take sha256sum of file and compare to check in one line?

I keep on finding myself wanting to download and check the integrity of the download immediately in a script, but I haven't been able to find the right incantation of sha256sum.

MY_SHA256=e147f0392686c40cfd7d5e6f332c6ee74c4eab4d24e2694b3b0a0c037bf51dc5
sha256sum some_binary | sha256sum --check ${MY_SHA256}

How can I take the sha256sum of a new file and compare it with a known hash immediately?


I have downloaded an archive file and an accompanying checksum file. Here is how I verify that the hash of the downloaded archive matches the hash from the downloaded checksum file:

echo "$(cat archive.tar.gz.sha256) archive.tar.gz" | sha256sum --check --status

The --status flag prevents all stdout output (more effective than --quiet). I then need to rely on the return code to determine if they matched, which is what I want anyway since I'm going to be using this in a script.


You can see that sha256sum --check takes the output of a previous (regular) sha256sum run: it takes hashes and filenames via stdin, and compares them against actual files.

So the obvious thing to do is to manually give it the output in the format it wants:

$ echo "da39a3ee5e6b4b0d3255bfef95601890afd80709  motd" | sha1sum --check
motd: OK

Example:

 echo "67574ee0039eaf4043a237e7c4b0eb432ca07ebf9c7b2dd0667e83bc3900b2cf kali-linux-2019.2-amd64.iso" | sha256sum -c

In case you have the sha256sum file, you can directly use it:

sha256sum -c "kali-linux-2019.2-amd64.iso.txt.sha256sum"

Explanation:

In the above example, you have

echo "<known SHA 256 sum of the file> <name of the file>" | sha256sum -c

sha256sum -c option can either read the SHA256 sum from a sha256sum file or from STDIN. In case you don't have the sha256sum file, then using the echo command you can provide the same details contained in a sha256sum file.

In case you have the sha256sum file, you can directly use it:

sha256sum -c "<sha256sum file name>"

Note:

Alternatively, you can use shasum -a 256 instead of sha256sum where -a specifies the algorithm to be used.