Karl Baker
Karl Baker

Reputation: 913

Linux bash: Compare hash strings without setting variables

I want a simple bash command to compare two hash values that outputs whether they are the same. Here's what I've tried:

md5sum file1 | awk '{print $1}' # outputs hash value without filename

md5sum file1 > md5sum file2 # no output even though files/hashes differ

I've tried variations on the following with no success so far:

[ md5sum states.txt | awk '{print $1}' == md5sum states_copy.txt | awk '{print $1}' ]`

[ (md5sum states.txt | awk '{print $1}') == (md5sum states_copy.txt | awk '{print $1}') ]

I'm open to a script or multi-line bash solution, or using shasum, but I'm new to Linux and bash so trying to keep it as simple as possible.

I'm running Ubuntu 18.04.

Upvotes: 1

Views: 7895

Answers (2)

Kent
Kent

Reputation: 195029

there are many ways to do it, since you used awk, you may try:

md5sum f1 f2|awk '{a[$1]}END{print NR==length(a)}'

If the two hashes are same, output 0 otherwise 1. you can add more files to md5sum:

md5sum f1 f2 f3...fn|awk '{a[$1]}END{print NR==length(a)}'

Upvotes: 1

KamilCuk
KamilCuk

Reputation: 140880

[ "$(<states.txt md5sum)" = "$(<states_copy.txt md5sum)" ]
  1. Use $(...) to get command output
  2. Remember to enclose $(...) inside "
  3. Bash test supports single = for string comparision, not double ==
  4. Redirect the files into md5sum using stdin and using < redirection.

Upvotes: 5

Related Questions