cmp Command

Purpose

Compares the contents of two files and reports the first character that differs.

Syntax

cmp-l -s File1 File2

Description

The cmp command compares files designated by the File1 and File2 parameters and writes the results to standard output. If you specify a - (minus sign) for either the File1 or File2 parameter, the cmp command reads standard input for that file. Only one file can be read from standard input. Under default conditions, the cmp command displays nothing if the files are the same. If they differ, the cmp command displays the byte and line number at which the first difference occurs. If the -l flag is specified and if one file is an initial subsequence of the other (that is, if the cmp command reads an end-of-file character in one file before finding any differences), the cmp command notes this. Normally, use the cmp command to compare non-text files and the diff command to compare text files.

Flags

Item Description
-l (Lowercase L) Displays, for each difference, the byte number in decimal and the differing bytes in octal.
-s Returns only an exit value. A value of 0 indicates identical files; value of 1 indicates different files; a value of 2 indicates inaccessible file or a missing option.

Exit Status

This command returns the following exit values:

Item Description
0 The files are identical.
1 The files are different. This value is given even if one file is an initial subsequence of the other (one file is identical to the first part of the other).
>1 An error occurred.

Examples

  1. To determine whether two files are identical, enter:
    cmp prog.o.bak prog.o
    This compares prog.o.bak and prog.o. If the files are identical, then a message is not displayed. If the files differ, then the location of the first difference is displayed; for example:
    prog.o.bak prog.o differ: char 4, line 1
    If the message cmp: EOF on prog.o.bak is displayed, then the first part of prog.o is identical to prog.o.bak, but there is additional data in prog.o.
  2. To display each pair of bytes that differ, enter:

    cmp  -l prog.o.bak prog.o

    This compares the files, and then displays the byte number (in decimal) and the differing bytes (in octal) for each difference. For example, if the fifth byte is octal 101 in prog.o.bak and 141 in prog.o, the cmp command displays:
    5 101 141
  3. To compare two files without writing any messages, enter:

    cmp  -s prog.c.bak prog.c

    This gives an exit value of 0 if the files are identical, a value of 1 if different, or a value of 2 if an error occurs. This form of the command is normally used in shell procedures. For example:

    if cmp  -s prog.c.bak prog.c
    then
    echo No change
    fi

    This partial shell procedure displays No change if the two files are identical.

Files

Item Description
/usr/bin/cmp Contains the cmp command.