0
0
Bash-scriptingHow-ToBeginner · 3 min read

How to Use diff in Bash: Compare Files Easily

Use the diff command in bash to compare two files line by line and see their differences. The basic syntax is diff file1 file2, which outputs the lines that differ between the two files.
📐

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 can modify the output format or behavior.

Common options include:

  • -u: Show unified diff (context around changes)
  • -c: Show context diff
  • --brief: Only report if files differ
bash
diff file1.txt file2.txt
💻

Example

This example compares two text files and shows their differences in a simple format.

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 directories instead of files without the -r option.
  • Not using quotes when file names contain spaces.
  • Expecting diff to show differences in a side-by-side format without using the -y option.

Example of wrong and right usage:

bash
diff file one.txt file two.txt
# Wrong: will treat 'file' and 'one.txt' as separate arguments

# Correct:
diff "file one.txt" "file two.txt"
📊

Quick Reference

OptionDescription
-uShow unified diff with context lines
-cShow context diff
-yShow side-by-side comparison
--briefOnly report if files differ
-rRecursively compare directories

Key Takeaways

Use diff file1 file2 to see line-by-line differences between two files.
Add -u for a unified diff that shows context around changes.
Quote file names with spaces to avoid errors.
Use -y for side-by-side comparison if preferred.
Remember diff works on files and directories with appropriate options.