How to verify a checksum using one command line?
You can create a simple function in your .bashrc
or .zshrc
configurations and run it in the following way:
sha256 <expected-sha-256-sum> <name-of-the-file>
It will compare the expected sha256 sum with the actual one in a single command.
The function is:
sha256() {
echo "$1 $2" | sha256sum --check
}
Please find more details here.
Q1: I'd like to know how to do this using a command that does not require copy and pasting of the first output's checksum (if it's possible).
Bash
provides no mechanism to recall any output from the previously run command. You have to capture it explicitly if you intend to act on it in any subsequent commands.
Q2: I'd like to know the simplest way to do this using a command that does require copy and pasting of the first output's checksum. (Simply attempting to use grep on a double‐quoted pasted checksum (i.e., as a string) doesn't work.)
So your only option here is to copy/paste the output from the previous command. With respect to why this wasn't working for you when you attempted it. This likely failed because when you use echo <sha1sum>
you introduced an additional character, a newline (\n
) which altered the checksum string.
When echoing strings to any of the hash functions like md5
or sha256sum
it's generally best to do an echo -n <..>
which tells echo
to omit appending a newline at the end of the string.
You can see how this can influence any calls to a hash function like so:
$ echo "blah" | sha256sum
41af286dc0b172ed2f1ca934fd2278de4a1192302ffa07087cea2682e7d372e3 -
$ echo -n "blah" | sha256sum
8b7df143d91c716ecfa5fc1730022f6b421b05cedee8fd52b1fc65a96030ad52 -
The true hash of the string 'blah' is the 2nd call.
Looks like you're checking matches. Did you consider using the -c
(--check
) option to sha256sum
?