Diff Command - Compare Files and Directories

Learn how to use the diff command to compare files and directories, identify differences, and generate patch files. Explore options for ignoring whitespace, case, and blank lines.

Diff Command Usage

The diff command is a powerful command-line utility used to compare files line by line and identify the differences between them. It is an essential tool for developers and system administrators for tracking changes, merging code, and creating patch files.

Comparing Files with Diff

The most basic usage of the diff command is to compare two files. The output will show the lines that need to be added, deleted, or changed to make the first file identical to the second.

# To view the differences between two files:
diff -u <file-1> <file-2>

Comparing Directories

diff can also be used to compare the contents of two directories recursively, highlighting files that are different or unique to each directory.

# To view the differences between two directories:
diff -ur <dir-1> <dir-2>

Ignoring Differences

Often, you may want to ignore certain types of differences to focus on the significant changes. diff provides options to ignore whitespace, blank lines, and case sensitivity.

# To ignore whitespace:
diff -ub <file-1> <file-2>

# To ignore blank lines:
diff -uB <file-1> <file-2>

# To ignore the differences between uppercase and lowercase:
diff -ui <file-1> <file-2>

Reporting File Status

You can use diff to simply report whether files differ or are identical, without showing the detailed changes.

# To report whether the files differ:
diff -q <file-1> <file-2>

# To report whether the files are identical:
diff -s <file-1> <file-2>

Diffing Command Output

A useful feature is the ability to compare the output of two commands or scripts directly.

# To diff the output of two commands or scripts:
diff <(command1) <(command2)

Generating Patch Files

The diff command is fundamental in creating patch files, which are used to apply changes from one version of a file to another.

# To generate a patch file from two files:
diff -Naur <file-1> <file-2> > <patch-file>

External Resources