When modifying configuration files, writing code, or managing backups, it is incredibly easy to lose track of what you actually changed. If a service suddenly stops working after an update, you need to quickly identify the exact lines that were altered between the old backup and the new configuration file.
In Linux, the easiest way to find the differences between two text files is by using the diff command. This built-in utility analyzes two files line-by-line and outputs exactly what was added, removed, or changed.
In this guide, you will learn how to effectively use the diff command in the Linux terminal.
How to Run a Basic File Comparison
To compare two files, you simply provide both file paths as arguments to the command.
- Open your terminal.
- Type the command using the following syntax:
diff file1.txt file2.txt - Press Enter.
The output will display the changes needed to make file1 identical to file2. You will see lines starting with < (which represent lines from the first file) and lines starting with > (which represent lines from the second file).
How to Make the Output Easier to Read (Unified Format)
The standard output of the diff command can be confusing for beginners. The most common and widely understood way to read file differences is the “Unified” format, which is the same format used by version control systems like Git.
- To view the differences in unified format, add the
-uflag:diff -u file1.txt file2.txt
In this output:
- Lines starting with a minus sign (
-) indicate text that was deleted from the first file. - Lines starting with a plus sign (
+) indicate text that was added to the second file. - Lines with no symbol are identical in both files and are simply shown to provide context.
How to Ignore Whitespace and Blank Lines
If you are comparing code or scripts, someone might have added a few extra spaces or blank lines. These formatting changes usually don’t affect how the file works, but they will clutter your diff output.
- To ignore changes in the amount of whitespace, use the
-bflag. - To ignore completely blank lines, use the
-Bflag. - You can combine these flags with the unified format for the cleanest possible output:
diff -u -b -B file1.txt file2.txt
This ensures you only see actual, meaningful changes to the text or code.