About

Script Categories

Shell Script To Delete Files In The First Directory Which Are Similarly Named In The Second Directory

Posted in Decision Making » File-management

A shell script to compare files in two directory and delete files in the first directory which are similarly named in the second directory. Following script uses for loop to compare files in a each directory.

#!/bin/bash
# Write a shell script that accepts two directory names as arguments and
# deletes those files in the first directory which are similarly named in
# the second directory.
SRC="$1"
DST="$2"
if [ $# -ne 2 ]
then
        echo "$(basename $0) dir1 dir2"
        exit 1
fi
 
if [ ! -d $SRC ]
then
        echo "Directory $SRC does not exists!"
        exit 2
fi
 
if [ ! -d $DST ]
then
        echo "Directory $DST does not exists!"
        exit 2
fi
 
for f in $DST/*
do
#echo Processing $f
        if [ -f $f ]
        then
                tFile="$SRC/$(basename $f)"
                if [ -f $tFile ]
                then
                        echo -n "Deleting $tFile..."
                        /bin/rm $tFile
                        [ $? -eq 0 ] && echo "done" || echo "failed"
 
                fi
        fi
done

Download - Email this to a friend - Printable version

Is your site working? Monitor Your Web Site 24/7. Get SMS alerts on server downtime! Free 30-day trial including 20 SMS!

Related Other Helpful Shell Scripts:

Leave a Reply

We encourage your comments, and suggestions. But please stay on topic, be polite, and avoid spam. Thank you very much for stopping by our site!

XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Tags: , , , , , , , , ~ Last updated on: July 15, 2008