The diff command is used to compare two files or directories line by line and show the differences between them. It’s widely used in development, scripting, and troubleshooting.
▶️ Basic Syntax
diff [options] file1 file2
📄 Simple Example
diff file1.txt file2.txt
Output shows:
- Lines only in
file1 - Lines only in
file2 - Where changes occurred
🔍 Useful Options
Side-by-side comparison
diff -y file1.txt file2.txt
Ignore whitespace
diff -w file1.txt file2.txt
Ignore case differences
diff -i file1.txt file2.txt
Show unified format (best for readability)
diff -u file1.txt file2.txt
✔ Commonly used for patches and code reviews
📂 Compare Directories
diff -r dir1 dir2
✔ Recursively compares all files
🧪 Practical Examples
Check config changes
diff -u old.conf new.conf
Compare backups
diff -r /backup1 /backup2
📌 Understanding Output
Example:
2c2
< old line
---
> new line
c= change<= from first file>= from second file
⚡ Highlight Differences with Color
Install tools like:
colordiff(wrapper for diff)
colordiff file1.txt file2.txt
⚠️ Common Issues
No output
✔ Files are identical
Large output
✔ Use:
diff -u file1 file2 | less
🧠 When to Use diff
- Comparing configuration files
- Reviewing code changes
- Debugging scripts
- Verifying backups
💡 Pro Tip
Use diff -u for clean, readable output—it’s the standard format used in patches and version control systems.