Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

When I generate checksums for my files, I have to do a bit of extra work to get them formatted properly:

CHECKSUM="$(shasum "$file" | cut -b 1-40)"
echo -n "$CHECKSUM" > "$file.sha"

This is to ensure that in the file, I only have the checksum itself (hence cut) and that at the end of the file, there's no newline (hence echo -n).

Validating the checksums also requires a bit extra work:

CHECKSUM="$(shasum "$file" | cut -b 1-40)"
echo -n "$CHECKSUM" | diff - "$file.sha"

Is there an easier, more compact way of creating and validating checksums without storing the path? I prefer not to store the path in the checksum along with the file as it makes the files less portable IMO.

share|improve this question
If you need the checksums for many files then it would be more efficient to run sha1sum over all files and make awk put each line in a single file: sha1sum * | awk ... – Hauke Laging Apr 28 '14 at 20:05
Would md5deep be helpful ? – Iain Apr 28 '14 at 20:21
up vote 4 down vote accepted

An obvious small improvement to

CHECKSUM="$(shasum "$file" | cut -b 1-40)"
echo -n "$CHECKSUM" > "$file.sha"


shasum "$file" | cut -b 1-40 >"$file.sha"

The trailing newline by cut can be avoided with `awk:

shasum "$file" | awk -v ORS="" '{print $1}'

A simpler form of

CHECKSUM="$(shasum "$file" | cut -b 1-40)"
echo -n "$CHECKSUM" | diff - "$file.sha"


if [ "$(shasum "$file" | cut -b 1-40)" = "$(<"$file.sha")" ]; then ...
share|improve this answer
shasum "$file" | cut -b 1-40 > "$file.sh" - Won't this append a newline at the end of the file by default? – Naftuli Tzvi Kay Apr 28 '14 at 19:33
@NaftuliTzviKay I guess you misunderstand the meaning of echo -n. That does not mean "strip off all trailing newlines". It means: "Do not add a newline" I.e. if there is a newline at the end of $CHECKSUM then both your and my solution write a trailing newline to the file. But who cares about trailing newlines when using $()? echo -n $CHECKSUM would strip off newlines, though. – Hauke Laging Apr 28 '14 at 19:36
My files end up being 41 bytes rather than the expected 40 bytes - trailing newline. – Naftuli Tzvi Kay Apr 28 '14 at 19:41
@NaftuliTzviKay Right. My $CHECKSUM explanation is correct but as $CHECKSUM does not appear in my code it is not helpful. But as the "$(<"$file.sha")" removes the newline this does not matter (unless you use the files in other ways, too). This problem can probably not be avoided wit cut. I will add an awk alternative to my answer. – Hauke Laging Apr 28 '14 at 19:50

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.