If it is ever desired to compare two directory trees in Linux then the file comparison utility diff can be used for this purpose. The Linux diff command provides options to check content based file differences along with new or missing files. In this article, we will learn quickly how to compare two directories in Linux using diff command.
Compare two directories in Linux using diff command
Here are the two directories that we will consider in this example :
$ ls dir1 dir1_1 new.txt
$ ls dir2 dir2_1 newfile.txt new.txt
The diff command in Linux provides an option -r using which the diff command recursively compares the subdirectories. So lets use this option here :
$ diff -r dir1 dir2 Only in dir1: dir1_1 Only in dir2: dir2_1 Only in dir2: newfile.txt
So we see that the missing files and directories were printed in the output.
Also, if there exists a file that is present in both the directories but has some text based differences then also -r option notifies the difference. Here is an example :
$ diff -r dir1 dir2 Only in dir1: dir1_1 Only in dir2: dir2_1 Only in dir2: newfile.txt diff -r dir1/new.txt dir2/new.txt 1c1 < Linux vs Windows --- > Linux and Windows
So we see that not only missing files were notified but the difference between matching files was also highlighted.
Now, unlike above, if it desired to have only notifications regarding which files differ in content (rather than difference being highlighted as above) then the option -q can be used.
Here is an example :
$ diff -qr dir1 dir2 Only in dir1: dir1_1 Only in dir2: dir2_1 Only in dir2: newfile.txt Files dir1/new.txt and dir2/new.txt differ
So this way diff utility can be used to not only compare file text but also to compare two directories in Linux for missing files.

