cmp Command in Linux with examples
cmp command in Linux/UNIX is used to compare the two files byte by byte and helps you to find out whether the two files are identical or not.
- When cmp is used for comparison between two files, it reports the location of the first mismatch to the screen if difference is found and if no difference is found i.e the files compared are identical.
- cmp displays no message and simply returns the prompt if the files compared are identical.
Syntax: cmp [OPTION]... FILE1 [FILE2 [SKIP1 [SKIP2]]] SKIP1 ,SKIP2 & OPTION are optional and FILE1 & FILE2 refer to the filenames .
The syntax of cmp command is quite simple to understand. If we are comparing two files then obviously we will need their names as arguments (i.e as FILE1 & FILE2 in syntax). In addition to this, the optional SKIP1 and SKIP2 specify the number of bytes to skip at the beginning of each file which is zero by default and OPTION refers to the options compatible with this command about which we will discuss later on. cmp Example : As explained that the cmp command reports the byte and line number if a difference is found. Now let’s find out the same with the help of an example. Suppose there are two files which you want to compare one is file1.txt and other is file2.txt :
$cmp file1.txt file2.txt
- If the files are not identical : the output of the above command will be :
$cmp file1.txt file2.txt file1.txt file2.txt differ: byte 9, line 2 /*indicating that the first mismatch found in two files at byte 20 in second line*/
- If the files are identical : you will see something like this on your screen:
$cmp file1.txt file2.txt $ _ /*indicating that the files are identical*/
Options for cmp command
1. -b(print-bytes) : If you want cmp displays the differing bytes in the output when used with -b option.
//...cmp command used with -b option...// $cmp -b file1.txt file2.txt file1.txt file2.txt differ: 12 byte, line 2 is 154 l 151 i /* indicating that the difference is in 12 byte ,which is 'l' in file1.txt and 'i' in file2.txt.*/
The values 154 and 151 in the above output are the values for these bytes, respectively. 2. -i [bytes-to-be-skipped] : Now, this option when used with cmp command helps to skip a particular number of initial bytes from both the files and then after skipping it compares the files. This can be done by specifying the number of bytes as argument to the -i command line option.