Per Mildner
Per Mildner

Reputation: 10487

Generating just a SHA-256 hash from the Linux command line

I'm looking for a single command that emits just the sha256 hash, as a hexadecimal number, of the contents of a single supplied file.

I am aware of shasum -a 256, openssl dgst -sha256, sha256sum et al. but they all emit other information together with the checksum and I would like to avoid the need for post-processing the result with sed or some such.

Upvotes: 5

Views: 8198

Answers (2)

KamilCuk
KamilCuk

Reputation: 141748

You may use:

sh -c 'shasum < "$1" | cut -d" " -f1' -- "$file"

Upvotes: 5

Per Mildner
Per Mildner

Reputation: 10487

The following perl one-liner actually seems to satisfy all my stated requirements:

perl -e 'use Digest::SHA;' -e 'use warnings;' -e 'use strict;' -e 'use autodie;' -e 'my $sha = Digest::SHA->new(256); open my $fh, $ARGV[0]; $sha->addfile($fh, "b"); print $sha->hexdigest . "\n";' "$file"

In particular it is safe for "funny" file names and can be used for arbitrary shell scripting, including as a find --exec argument (which is one thing I need it for).

(I have not written in Perl for a very long time, so the above can probably be improved.)

Upvotes: 0

Related Questions