diff (Differential)
The diff command is used to compare two files line by line and display the differences between them. It tells you which lines in one file must be changed to make it identical to the second file. This is the foundation of version control systems like Git.
1. Basic Usage
diff [options] file1 file2
<denotes lines from the first file.>denotes lines from the second file.
2. Key Options
| Option | Name | Description |
|---|---|---|
-c |
context | Provides a few lines of context around each difference. |
-u |
unified | Unified format. The standard format used for creating patches and in Git. |
-y |
side-by-side | Displays the differences in two columns. |
-i |
ignore-case | Ignores case differences in file contents. |
-w |
ignore-all-space | Ignores all white space when comparing lines. |
-r |
recursive | Directory comparison. Compares folders and their subfolders. |
3. Practical Examples
① Visualizing differences side-by-side
diff -y original.c updated.c
② Generating a patch file (Unified format)
diff -u config.old config.new > config.patch
③ Comparing two directories
diff -qr dir1/ dir2/
# -q shows only whether files differ, not the actual content changes.
4. [Tip] Symbolic Indicators
a: Additionc: Changed: Deletion Modern developers often usecolordifforgit difffor colorized, easier-to-read comparisons.