Ubuntu – How to verify a checksum using one command line

checksumcommand lineUbuntu

Suppose I type and run the following command:

sha256sum ubuntu-18.04.1-desktop-amd64.iso

After a delay, this outputs the following:

5748706937539418ee5707bd538c4f5eabae485d17aa49fb13ce2c9b70532433  ubuntu-18.04.1-desktop-amd64.iso

Then, I realize that I should have typed the following command to more rapidly assess whether the SHA‐256 hash matches:

sha256sum ubuntu-18.04.1-desktop-amd64.iso | grep 5748706937539418ee5707bd538c4f5eabae485d17aa49fb13ce2c9b70532433

Is there a way to act on the first output without using the sha256sum command to verify the checksum a second time (i.e., to avoid the delay that would be caused by doing so)? Specifically:

  1. 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).
  2. 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.)

Best Answer

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.

Related Question