Generate and Verify File Checksum using cksum on Linux

Generate and Verify File Checksum using cksum on Linux

The cksum command calculates a checksum for a file, which helps detect accidental changes to its contents. For example, a checksum can be used to check whether a file was modified or corrupted during transfer over a network. This tutorial shows how to generate and verify a file checksum using cksum on Linux.

Generate checksum

Create a new file for testing:

printf 'Hello world' > test.txt

The cksum command can be used to generate a checksum of a file and print the result in the terminal:

cksum test.txt

The output contains the checksum, file size in bytes, and filename:

3178086752 11 test.txt

Verify checksum

Save the generated checksum in a file for later comparison:

cksum test.txt > test.cksum

To verify the file later, generate its checksum again and compare it with the saved checksum using diff:

cksum test.txt > test-new.cksum
diff test.cksum test-new.cksum

If the file has not changed, diff produces no output because both checksum files are identical.

Modify the file by appending additional content:

printf 'Hi' >> test.txt

Generate and compare the checksum again:

cksum test.txt > test-new.cksum
diff test.cksum test-new.cksum

Output:

1c1
< 3178086752 11 test.txt
---
> 1886422834 13 test.txt

The difference indicates that the checksum no longer matches the previously recorded value and that the file contents have changed.

Leave a Comment

Cancel reply

Your email address will not be published.