cmp Command in Linux
Summary
The cmp command in Linux is a powerful utility used to compare two files byte by byte. It is primarily used to identify differences between binary or text files, making it invaluable for tasks such as verifying file integrity or identifying modifications.
Introduction
The cmp command stands for "compare." It reads two files and reports the first byte and line number where a difference is found. If the files are identical, it reports nothing. If one file is shorter than the other, cmp will report an end-of-file condition. This command is a fundamental tool for anyone working with file manipulation and verification in a Linux environment. Unlike diff, cmp is specifically designed to find the first difference rather than a comprehensive list of all differences.
Use case and Examples
Comparing two identical files
Iffile1.txt and file2.txt are identical, cmp will output nothing. Comparing two different files
Iffile_a.txt and file_b.txt differ, cmp might output: file_a.txt file_b.txt differ: byte 4, line 1. This indicates the first difference is at byte 4 on line 1. Comparing a file to standard input
This allows for on-the-fly comparison against typed input.Handling End-of-File (EOF)
Ifshort_file.txt is shorter than long_file.txt, the output might be: cmp: EOF on short_file.txt. Commonly used flags
| Flag | Description | Example |
|---|---|---|
-b or --print-bytes | Prints the differing bytes in octal format. | cmp -b file1.txt file2.txt |
-l or --verbose | Prints the byte number (decimal) and the differing byte values (octal) for each difference. | cmp -l file1.txt file2.txt |
-s or --quiet or --silent | Suppresses all normal output; only returns an exit status. Useful for scripting. | cmp -s file1.txt file2.txt; echo $? (The $? will be 0 if files are identical, 1 if different). |
-i SKIP1[:SKIP2] or --ignore-initial=SKIP1[:SKIP2] | Skip the first SKIP1 bytes of the first input and SKIP2 bytes of the second input. | cmp --ignore-initial=10 file1.txt file2.txt |