Tuesday, September 25, 2012

Comparing directories using 'diff' command

'diff' command can be used to compare not just Files but also Directories/Folders as well.
Following is a self-explanatory demonstration on how the 'diff' command can used to compare or find differences between 2 folders (folder1 & folder2).

[root@hostxyz folder1]# ls -l
total 16
-rw-r--r-- 1 root root 3 Sep 24 12:29 oraclelinux
-rw-r--r-- 1 root root 3 Sep 24 12:28 redhat
-rw-r--r-- 1 root root 3 Sep 24 12:28 suse
-rw-r--r-- 1 root root 3 Sep 24 12:29 ubuntu
[root@hostxyz folder1]# for i in `ls`; do echo $i   : `cat $i`; done      # Contents of all files in folder1
oraclelinux : OS
redhat : OS
suse : OS
ubuntu : OS
[root@hostxyz folder1]# cd ../folder2
[root@hostxyz folder2]# ls -l
total 16
-rw-r--r-- 1 root root 17 Sep 24 12:34 CentOS
-rw-r--r-- 1 root root 17 Sep 24 12:30 oraclelinux
-rw-r--r-- 1 root root  3 Sep 24 12:29 redhat
-rw-r--r-- 1 root root 17 Sep 24 12:30 ubuntu
[root@hostxyz folder2]# for i in `ls`; do echo $i   : `cat $i`; done     # Contents of all files in folder2
CentOS : Operatins system
oraclelinux : Operating system
redhat : OS
ubuntu : Operating system

[root@hostxyz folder2]# diff /var/folder1 /var/folder2 -r --brief     
Only in /var/folder2: CentOS
Files /var/folder1/oraclelinux and /var/folder2/oraclelinux differ
Only in /var/folder1: suse
Files /var/folder1/ubuntu and /var/folder2/ubuntu differ
[root@hostxyz folder2]#

Options used :
 -r  :      Searched recursively through the directories.
--brief : Only shows the names of the files that differ. If you want details of the content that differs, remove this option.