Shell Script to Check for New files in a Directory-DecodingDevOps

Shell Script to Check for New files in a Directory-DecodingDevOps

Using Linux diff command we can check for new files in a directory. Linux diff command is used to differentiate between two files. Diff command will print out the difference between the two files. Here we are using  difference between the two files feature to check whether new files in a directory created or not.

in the below example i will show you if any new file or files created in /etc folder. to check for New files in a Directory we have to follow below steps.

  • list the files in the directory /etc and copy that list of files into a  base file ex: oldfiles
  • write a shell script to list the files in a new file ex: newfiles  and compare it with base file oldfiles

Create a Base file

ls -A /etc > oldfiles

base file will have all our older files and folders information. Above command will creates a base file to compare when you use diff command.

Write Shell Script to Check for New files in a Directory

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

BASEDIR=”/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 $BASEDIR > newfiles
This will create the second file that can be compared to the base file that was originally created.

DIRDIFF=$(diff oldfiles newfiles | 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.

for file in $DIRDIFF
do
if [ -e $BASEDIR/$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.

Test the Shell 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. it will print the newly created files in /etc directory.

  • shell to script to find new files a directory
  • Linux shell to script to find new files a directory
  • Shell Script to Check for New files in a Directory
  • how to check for New files in a Directory in linux

Leave a Reply

Your email address will not be published. Required fields are marked *