0
0
Linux-cliHow-ToBeginner · 3 min read

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 -a option, which treats them as text.
  • Not using quotes around filenames with spaces.
  • Expecting diff to 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

OptionDescription
-uShow unified diff (context around changes)
-cShow context diff with more lines around changes
-iIgnore case differences
-wIgnore all whitespace
-rRecursively compare directories
-qReport 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.