diff command
diff
- compare files line by line
The diff
command in Linux is a utility used to compare two files and display their differences. It’s very useful for spotting changes in code, configuration files, or any text data.
Usage: diff [OPTION]... [FILES]...
OPTION
: Flags which enhances thediff
abilities.FILES
: The file(s) to compare.
Common Options
Option | Description |
---|---|
-u | Unified output with context |
-y | Side-by-side output |
-i | Ignore case differences |
-w | Ignore all whitespace |
-b | Ignore changes in whitespace amount |
-r | Recursively compare directories |
-q | Brief mode (just say if files differ) |
Examples
-
Basic Comparison
Run
diff
with two files to see how they differ.$ diff file1.txt file2.txt
- Sample files:
file1.txt
:apple\nbanana\ncherry
file2.txt
:apple\norange\ncherry
- Output:
2c2
< banana
---
> orange - Explanation:
2c2
: Line 2 infile1
changed to line 2 infile2
.< banana
: Line fromfile1
.> orange
: Line fromfile2
.
If the files are identical, there’s no output.
- Sample files:
-
Unified Output Format
Use
-u
for a more readable "unified" format, showing context around changes.$ diff -u file1.txt file2.txt
- Output:
--- file1.txt 2025-03-29 10:00:00
+++ file2.txt 2025-03-29 10:01:00
@@ -1,3 +1,3 @@
apple
-banana
+orange
cherry - Explanation:
-
lines are removed fromfile1
.+
lines are added infile2
.- Context lines (unchanged) are shown for reference.
- Output:
-
Side-by-Side Output
Use
-y
to display differences in two columns.$ diff -y file1.txt file2.txt
- Output:
apple apple
banana | orange
cherry cherry - Explanation:
|
indicates a difference.- Identical lines align without markers.
- Output:
-
Ignoring Case
Use
-i
to ignore case differences.$ diff -i file1.txt file2.txt
- If
file1.txt
has "Apple" andfile2.txt
has "apple",-i
treats them as the same.
- If
-
Ignoring Whitespace
Use
-w
to ignore all whitespace differences or-b
to ignore changes in the amount of whitespace.$ diff -w file1.txt file2.txt
- Ignores spaces or tabs (e.g., "hello world" vs. "helloworld").
-
Recursive Directory Comparison
Use
-r
to compare directories and their contents.$ diff -r dir1/ dir2/
- Compares all files in
dir1
anddir2
, reporting differences.
- Compares all files in
-
Brief Output
Use
-q
to only report whether files differ, not how.$ diff -q file1.txt file2.txt
- Output:
Files file1.txt and file2.txt differ
(or nothing if identical).
- Output:
To get help related to the diff
command use --help
option
$ diff --help