jump to navigation

Shell script to compare two directories and copy missing files January 20, 2010

Posted by Anoop Somasundaran in Linux, Unix.
Tags: ,
4 comments

The following shell script compares two directories and copies missing files from the source directory to the destination directory. Please note that script doesn’t compare sub-directories. You can execute the scrip by supplying two parameters – source directory and destination directory.

/bin/bash
#####################################################################
# Created by Anoop Somasundaran
# This script takes two parameters- from_directory and to_directory.
# It finds the file differences and copy the files to the destination directory.
# Only missing files are copied. Sub directories are not considered
#####################################################################

# Check the number of input parameters. If two parameters are given go ahead, else exit
if [ $# -eq 2 ]
then
FROMDIR=$1
TODIR=$2
else
echo "Usage: script.sh fromdir todir"
exit
fi

# Validate from_directory
if [ ! -d "${FROMDIR}" ]
then
echo "Directory ${FROMDIR} does not exist!!"
exit
fi

# Validate to_directory
if [ ! -d "${TODIR}" ]
then
echo "Directory ${TODIR} does not exist!!"
exit
fi

cd ${FROMDIR}
for i in `find . -type f`
do
if [ ! -f ${TODIR}/$i ]
then
cp $i ${TODIR}/$i
fi

done

How to run the above script?

1) Copy the above script into a .sh file (script.sh)
2) You need to supply the complete path for source and destination directories while running the script.

$sh /home/script.sh /tmp/test1/ /tmp/test2/