Skip to content

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

cmp file1.txt file2.txt
If file1.txt and file2.txt are identical, cmp will output nothing.

Comparing two different files

cmp file_a.txt file_b.txt
If file_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

cmp file.txt -
This will wait for you to type in standard input. After typing the content and pressing Ctrl+D to signal the end of input, `cmp` compares it against `file.txt`.
This allows for on-the-fly comparison against typed input.

Handling End-of-File (EOF)

cmp short_file.txt long_file.txt
If short_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


Share on Share on

Comments