diff
Command: Comparing Files
Summary
The diff
command is a powerful utility for comparing files line by line and highlighting the differences between them. It is commonly used to identify changes made to files, generate patches, and resolve merge conflicts.
Introduction
The diff
command is a fundamental tool in any Linux user's arsenal. It allows you to compare two files (or even directories) and see precisely what has changed. This is invaluable for tracking revisions, understanding code modifications, and many other tasks. The output of diff
shows the lines that differ between the files, along with symbols indicating whether lines were added, deleted, or changed.
Use case and Examples
Basic Usage: Comparing Two Files
This command comparesfile1.txt
with file2.txt
and displays the differences in the standard diff
format. Creating a Patch File
This creates a "unified diff" (using the-u
flag) and saves the output to file.patch
. This patch file can then be used with the patch
command to apply the changes from file2.txt
to file1.txt
. This is useful for distributing changes to code. Comparing Directories
The-r
flag recursively compares all files in dir1
and dir2
. This is very helpful for identifying all the differences across entire directory structures. Ignoring White Space Differences
This command will comparefile1.txt
and file2.txt
, ignoring differences in the amount of whitespace. This can be useful when only the content matters, not the formatting. Commonly used flags
Flag | Description | Example |
---|---|---|
-i | Ignore case differences. | diff -i file1.txt file2.txt |
-w | Ignore all whitespace. | diff -w file1.txt file2.txt |
-u | Output in unified format (creates a patch). | diff -u file1.txt file2.txt |
-r | Recursively compare directories. | diff -r dir1 dir2 |
-q | Output only whether files differ. Suppresses detailed output. | diff -q file1.txt file2.txt |
-y | Output in side-by-side format. | diff -y file1.txt file2.txt |