0
0
Linux CLIscripting~5 mins

diff for file comparison in Linux CLI - Commands & Configuration

Choose your learning style9 modes available
Introduction
Sometimes you need to see what changed between two files. The diff command helps by showing line-by-line differences so you can quickly spot changes.
When you want to compare two versions of a configuration file to find what changed.
When you need to check differences between two text documents before merging them.
When you want to verify if two files are exactly the same or have differences.
When you want to review code changes manually without using a graphical tool.
When you want to create a patch file showing changes between two files.
Commands
This command compares file1.txt and file2.txt and shows the differences line by line.
Terminal
diff file1.txt file2.txt
Expected OutputExpected
1c1 < Hello world --- > Hello World!
The -u flag shows differences in a unified format, which is easier to read and commonly used for patches.
Terminal
diff -u file1.txt file2.txt
Expected OutputExpected
--- file1.txt 2024-06-01 12:00:00.000000000 +0000 +++ file2.txt 2024-06-01 12:01:00.000000000 +0000 @@ -1 +1 @@ -Hello world +Hello World!
-u - Show differences in unified format
The -q flag tells diff to only report if files differ, without showing the details.
Terminal
diff -q file1.txt file2.txt
Expected OutputExpected
Files file1.txt and file2.txt differ
-q - Report only if files differ
Key Concept

If you remember nothing else from diff, remember: it shows exactly what lines changed between two files.

Common Mistakes
Running diff without specifying both file names
diff needs two files to compare; missing one causes an error.
Always provide two file names like diff file1.txt file2.txt
Expecting diff to show differences when files are identical
diff shows no output if files are exactly the same, which can be confusing.
Use diff -q to get a clear message if files differ or not.
Not using -u flag when creating patches
Without -u, the output is harder to read and not suitable for patch tools.
Use diff -u for unified format when sharing or applying patches.
Summary
Use diff file1.txt file2.txt to see line-by-line differences between two files.
Use diff -u for a unified, easier-to-read difference format.
Use diff -q to quickly check if files differ without details.