Text
diff
Compare files line by line.
Additional Notes
diff compares files line by line and prints the differences. It supports several output formats: normal, context (-c), and unified (-u). Unified diffs are the most common because they are compact and can be applied with patch.
diff compares text. To compare directories recursively, add -r; to produce a reusable patch, use -u and redirect the output to a file.
Syntax
diff [options] FILE1 FILE2
Parameters
options: Flags that change howdiffbehaves.FILE1,FILE2: The files (or directories, with-r) to compare.
Common Options
-u: Unified diff output (the standard patch format).-c: Context diff output with surrounding lines.-r: Compare directories recursively.-q: Report only whether files differ, not the details.-y: Side-by-side output.-i: Ignore case differences.-w: Ignore all whitespace.-B: Ignore blank lines.--color: Colorize output when supported.--from-file=FILE: CompareFILEagainst every following argument.
Examples
diff old.txt new.txt
Show normal-format differences between two files.
diff -u old.txt new.txt
Show a unified diff with a few context lines.
diff -u old.txt new.txt > changes.patch
Save a unified diff as a patch file.
diff -qr dir-a dir-b
Recursively report which files differ between two directories without showing the content.
diff -y file1 file2
Show the two files side by side.
diff -uw script.sh script.new
Compare while ignoring whitespace differences.
Applying a Patch
patch < changes.patch
Apply a unified diff created earlier with diff -u.
patch -R < changes.patch
Reverse an already-applied patch.
Practical Notes
- Unified diffs from
diff -uare readable and are whatgit diffproduces. - Use
-rto diff whole directory trees; combine with-qfor a quick "what changed" list. patchappliesdiff -uoutput; keep the original file name forpatchto find it.- Use
-w/-iwhen you only care about real logic changes, not formatting.