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

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
Get the latest tutorials on SysAdmin, Linux/Unix, Open Source, and DevOps topics:
Category List of Unix and Linux commands
File Management cat
Firewall Alpine Awall CentOS 8 OpenSUSE RHEL 8 Ubuntu 16.04 Ubuntu 18.04 Ubuntu 20.04
Network Utilities dig host ip nmap
OpenVPN CentOS 7 CentOS 8 Debian 10 Debian 8/9 Ubuntu 18.04 Ubuntu 20.04
Package Manager apk apt
Processes Management bg chroot cron disown fg jobs killall kill pidof pstree pwdx time
Searching grep whereis which
User Information groups id lastcomm last lid/libuser-lid logname members users whoami who w
WireGuard VPN Alpine CentOS 8 Debian 10 Firewall Ubuntu 20.04
0 comments… add one

Leave a Reply

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

Use HTML <pre>...</pre>, <code>...</code> and <kbd>...</kbd> for code samples.