jump to navigation

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

Posted by Anoop Somasundaran in Linux, Unix.
Tags: ,
trackback

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/

Advertisements

Comments»

1. Josef - June 3, 2010

What’s the benefit compared to use rsync?

Thanks

2. Zvika - May 31, 2011

You can just use:
$ cp -u sourcedir/ destdir/

To also copy subdirectories, use:
$ cp -ur sourcedir/ destdir/

Johny - January 28, 2013

cool & simple 🙂

3. script to download new files - August 23, 2011

[…] listing of both, I'd just compare both directory listings, and copy what's missing. This page https://expertodev.wordpress.com/2010…missing-files/ has something that should get you […]


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: