Compare Two Directories on Linux

Compare Two Directories on Linux

Whether you're a system administrator, a software developer, or simply a Linux enthusiast, having the ability to compare directories is a valuable skill. It can help to find variations between directories, locate missing or redundant files, ensure that data is in sync between different locations, identify discrepancies in system configurations, or ensure data consistency in backups. This tutorial shows how to compare two directories on Linux.

Suppose we have two directories organized in a hierarchical structure:

test1/
├── data1/
│   ├── file11.txt
├── data2/
│   └── file21.txt
├── file1.txt
├── file2.txt
test2/
├── data1/
│   ├── file11.txt
├── data2/
│   └── file22.txt
├── file1.txt
├── file2.txt

Directory hierarchy can be created using these commands:

mkdir -p test1/data1 test1/data2 test2/data1 test2/data2
touch test1/data1/file11.txt test1/data2/file21.txt test1/file1.txt test1/file2.txt
touch test2/data1/file11.txt test2/data2/file22.txt test2/file1.txt
echo 'testing' > test2/file2.txt

Note that test2/file2.txt file contains content, while test1/file2.txt file does not.

One of the most convenient ways to get a quick overview of the differences between two directories is by using the diff command that available by default on most Linux distributions. It is a standard Linux utility for comparing text files and directories.

To compare two directories with diff, use the following command:

diff -qr test1 test2
  • -q - option stands for "quiet" and provides a brief summary of the differences, making it easier to spot variances between the directories. Instead of showing the specific content differences line by line, it simplifies the output to only reveal which files or directories differ, without displaying the actual changes within those files.
  • -r - option tells diff to perform a recursive comparison of the directories, including subdirectories, and their contents.

Here's the output:

Only in test1/data2: file21.txt
Only in test2/data2: file22.txt
Files test1/file2.txt and test2/file2.txt differ

Leave a Comment

Cancel reply

Your email address will not be published.