Using diff to Compare Directories

by mike on December 2, 2011

The diff command compares two files or directories and returns the differences.  This provides you a way to monitor changes in an important directory like /etc which houses most configuration files on a Linux system.  In order for this to work properly you will need to create a file that lists the content of the /etc directory so that you can make a comparison.

1. Create a directory in /opt to work from.

mkdir /opt/dircheck
cd /opt/dircheck

ls -A /etc > fileorg
This creates the base file to compare to when you use diff.

2. Now create the script in the /opt/dircheck directory.

#!/bin/sh
MONDIR="/etc"
ls -A $MONDIR > filetest
DIRDIFF=$(diff fileorg filetest | cut -f 2 -d "")
for file in $DIRDIFF
do
if [ -e $MONDIR/$file ]
then
echo $file
fi
done

MONDIR=”/etc”
This creates a variable that allows you to select the directory that you want to monitor and that variable is then used throughout the script.

ls -A $MONDIR > filetest
This will create the second file that can be compared to the base file that was origially created.

DIRDIFF=$(diff fileorg filetest | cut -f 2 -d “”)
This is the actual command to compare the files.  Notice that the diff output is sent to a pipe which will cut out the 2nd field (-f 2) and use whitespace to determine the location of the fields (-d “”).  This information is cut out as it basically tells you the files have different names, an issue you really do not need.

for file in $DIRDIFF
do
if [ -e $MONDIR/$file ]
then
echo $file
fi
done
What this does is perform a test to see if the new file was actually created and then print that file name to screen.

3. Test the script
Run the script the first time and you should see no output as nothing has changed.   Create a new file in the /etc directory and then run the script again.
touch /etc/t5

Comments on this entry are closed.

Previous post:

Next post: