The cmp
command is used to compare two files and check if they are identical or different. It is a useful tool for verifying that two files contain the same data. The command compares the contents of two files byte by byte and reports the first byte that differs between the two files.
Overview
The basic syntax for using cmp
is as follows:
cmp [OPTION]... FILE1 [FILE2 [SKIP1 [SKIP2]]]
Here, FILE1
and FILE2
are the two files that need to be compared. If FILE2
is not specified, cmp
compares FILE1
with the standard input. SKIP1
and SKIP2
are the number of bytes to skip from the beginning of FILE1
and FILE2
, respectively.
If cmp
finds a difference between the files, it prints the byte offset and the differing byte values in octal format. If the files are identical, cmp
produces no output.
Examples
- Compare two files:
$ cmp file1.txt file2.txt
This command will compare the contents of file1.txt
and file2.txt
. If the files differ, cmp
will output the byte offset and the differing byte values.
- Compare files with different byte offsets:
$ cmp file1.txt file2.txt 10 20
This command will compare the contents of file1.txt
and file2.txt
, skipping the first 10 bytes in file1.txt
and the first 20 bytes in file2.txt
.
- Compare a file with standard input:
$ cmp file1.txt -
This command will compare the contents of file1.txt
with the standard input. The hyphen (-) represents the standard input.
Options
The following table lists the available options for the cmp
command:
Option | Description |
---|---|
-b, –print-bytes | Print differing bytes in octal format |
-i, –ignore-initial=NUM | Ignore the first NUM bytes in both files |
-l, –verbose | Print all differing bytes |
-n, –bytes=NUM | Compare up to NUM bytes |
-s, –quiet, –silent | Suppress output |
Troubleshooting tips
- If
cmp
produces no output, the files are identical. - If
cmp
reports a difference, check the byte offset and the differing byte values to identify the location and nature of the difference. - If
cmp
hangs or takes a long time to complete, try specifying a smaller number of bytes to compare using the-n
option. - If
cmp
reports an error message, check that the files exist and that you have permission to read them.
Notes
- The
cmp
command is not designed to compare binary files. Use thediff
command instead. - The
cmp
command is case-sensitive. To perform a case-insensitive comparison, use the--ignore-case
option. - The
cmp
command can be used to compare files of different sizes. If one file is shorter than the other,cmp
reports a difference at the first differing byte.