Newline
Understand that the echo is adding a newline at the end which changes the hash:
$ echo test | sha1sum
4e1243bd22c66e76c2ba9eddc1f91394e57f9f83 -
$ echo -n test | sha1sum
a94a8fe5ccb19ba61c4c0873d391e987982fbbd3 -
Answer
But no, there is no way to make sha1sum to print only the hash. The reason is that the line is actually an encoded string. The line could start with a \
and the second space (yes, there are two) between the hash and the filename could become a *
to indicate a binary
hash (useful in DOS):
$ echo "hello" >'a\file'
$ md5sum -b 'a\file'
\b1946ac92492d2347c6235b4d2611184 *a\\file
So, no, it is not a good idea to try to parse that output without understanding the above.
Alternatives
A couple of simpler solutions on other languages are:
perl
$ echo "test" | perl -le 'use Digest::SHA qw(sha1_hex); print sha1_hex(<>);'
4e1243bd22c66e76c2ba9eddc1f91394e57f9f83
Or (for longer input, less memory used), write to a file (lets call it sha1.perl
):
use Digest::SHA qw(sha1_hex);
$state = Digest::SHA->new(sha1);
for (<>) { $state->add($_) }
print $state->hexdigest, "\n";
Execute it:
$ echo "test" | perl sha1.perl
4e1243bd22c66e76c2ba9eddc1f91394e57f9f83
php
$ echo "test" | php -r '$f = fgets(STDIN); echo sha1($f),"\n";'
4e1243bd22c66e76c2ba9eddc1f91394e57f9f83
python
Write this to a file (lets call it sha1.py
):
import hashlib
m = hashlib.sha1()
import sys
for line in sys.stdin:
m.update(line)
print m.hexdigest()
Use it:
$ echo "test" | python sha1.py
4e1243bd22c66e76c2ba9eddc1f91394e57f9f83
man sha1sum
implies (not explicitly) when-
is used.-
means the sum was created using stdin? Is it possible to omit the-
using onlysha1sum
?