Bash diff Command - Compare Files
Using the diff Command
The diff command compares two files line by line and shows which lines are different.
The examples below use these two files:
colors1.txt
red
green
blue
colors2.txt
red
yellow
blue
Basic Usage
Give diff two files. Lines that start with < are only in the first file, and lines that start with > are only in the second:
Example: Compare Two Files
diff colors1.txt colors2.txt
2c2
< green
---
> yellow
2c2 means "line 2 in the first file was changed into line 2 in the second file". You will also see a (added) and d (deleted).
If the files are the same, diff prints nothing.
Unified Format (-u)
Use -u to show the changes with some surrounding lines. Removed lines start with - and added lines start with +.
This is the format used by Git and most code review tools:
Example: Unified Format
diff -u colors1.txt colors2.txt
--- colors1.txt 2026-11-04 10:00:00.000000000 +0100
+++ colors2.txt 2026-11-04 10:05:00.000000000 +0100
@@ -1,3 +1,3 @@
red
-green
+yellow
blue
Only Say If Files Differ (-q)
Use -q when you only want to know if the files are different, not how:
Example: Quick Check
diff -q colors1.txt colors2.txt
Files colors1.txt and colors2.txt differ
Ignore Case and Spaces
Use -i to ignore upper and lower case, and -w to ignore all spaces:
Example: Ignore Case
echo "Hello" > a.txt
echo "HELLO" > b.txt
diff -i a.txt b.txt
No output means the files are the same when case is ignored.
Use diff in Scripts
diff returns an exit code: 0 if the files are the same, and 1 if they are different. You can use this in an if statement:
Example: Check in an if Statement
if diff -q colors1.txt colors2.txt > /dev/null; then echo "Same"; else echo "Different"; fi
Different
Options Overview
-u: Unified format, with lines marked + or --q: Only report whether the files differ-i: Ignore upper and lower case-w: Ignore all spaces-r: Compare folders, including sub-folders