How to Use diff Command in Linux: Syntax and Examples
The
diff command in Linux compares two files line by line and shows the differences. Use diff file1 file2 to see what changes are needed to make the files identical.Syntax
The basic syntax of the diff command is:
diff [options] file1 file2
Here, file1 and file2 are the two files you want to compare. Options modify how differences are shown.
bash
diff [options] file1 file2
Example
This example compares two text files and shows the differences line by line.
bash
echo -e "apple\nbanana\ncherry" > file1.txt echo -e "apple\nblueberry\ncherry" > file2.txt diff file1.txt file2.txt
Output
2c2
< banana
---
> blueberry
Common Pitfalls
Common mistakes when using diff include:
- Comparing binary files without
-aoption, which treats them as text. - Not using quotes around filenames with spaces.
- Expecting
diffto merge files; it only shows differences.
bash
diff file1 file2 # Wrong if files have spaces in names # Correct usage: diff "file 1.txt" "file 2.txt"
Quick Reference
| Option | Description |
|---|---|
| -u | Show unified diff (context around changes) |
| -c | Show context diff with more lines around changes |
| -i | Ignore case differences |
| -w | Ignore all whitespace |
| -r | Recursively compare directories |
| -q | Report only if files differ, no details |
Key Takeaways
Use
diff file1 file2 to see line-by-line differences between two files.Add
-u option for a clearer unified diff format showing context.Always quote filenames with spaces to avoid errors.
diff only shows differences; it does not merge files.Use options like
-i and -w to ignore case or whitespace differences.