cmp - macOS


Overview

The cmp command in macOS is a utility mainly used for comparing two files byte by byte. It is typically utilized to determine whether two files are identical or to find the location of the first difference between them. It is most effective in contexts such as debugging, checking data integrity, and automating tasks that require validation of file duplication or modification.

Syntax

The basic syntax of the cmp command is as follows:

cmp [options] file1 file2
  • file1: The first file to compare.
  • file2: The second file to compare.

Options/Flags

cmp includes several options that modify its behavior:

  • -b, –print-bytes: Print the differing bytes.
  • -i SKIPLIST, –ignore-initial=SKIPLIST: Skip a specified number of bytes in one or both files (format: N or N1:N2).
  • -l, –verbose: Output byte numbers and differing byte values.
  • -n LIMIT, –bytes=LIMIT: Compare at most LIMIT bytes.
  • -s, –quiet, –silent: Do not output anything; just return an exit status.
  • -v, –version: Display version information and exit.
  • -h, –help: Display a help message and exit.

Examples

  • Basic Comparison: Determine if two files are the same:
    cmp file1.txt file2.txt
    
  • Verbose Output: Identify where the files differ:
    cmp -l file1.txt file2.txt
    
  • Ignoring Initial Bytes: Skip the first 100 bytes of each file before comparing:
    cmp -i 100 file1.txt file2.txt
    
  • Limiting Byte Comparison: Compare only the first 150 bytes of each file:
    cmp -n 150 file1.txt file2.txt
    

Common Issues

  • Binary Files: cmp might produce unintelligible output when used with binary files. To handle binary comparisons, it’s often better to use the -l or -b option.

  • File Permissions: Lack of permissions to read one of the files leads to Permission denied error.

    Solution: Ensure you have proper read permissions on the files being compared.

Integration

cmp can be combined with other commands in scripts or command chains:

# Use cmp in a script to check if two files are identical
if cmp -s file1.txt file2.txt; then
    echo "Files are identical."
else
    echo "Files differ."
fi
  • diff: Compare files line by line.
  • md5, sha1sum: Generate cryptographic hashes to verify file integrity.

For further details, refer to the official documentation or manual pages (man cmp) on your Mac.