postheadericon Write a script to copy the file system from two directories to a new directory in such a way that only the latest file is copied in case there are common files in both the directories.

# read directory name
echo "Enter First Directory : \c"
read dir1

echo "Enter Second Dirctory : \c"
read dir2

# check inputed name is directory or not
if [ ! -d $dir1 ]
then
echo "DIRECTORY [ $dir1 ] NOT EXIST"
exit 1
fi


if [ ! -d $dir2 ]
then
echo "DIRECTORY [ $dir2 ] NOT EXIST"
exit 1
fi


# copy all file names in to a text file
ls $dir1 > dir1.txt
ls $dir2 > dir2.txt

mkdir TargetDir

for FileFromDir1 in `cat dir1.txt`
do
flag=0
for FileFromDir2 in `cat dir2.txt`
do
# compare file name is same or not
if [ "$FileFromDir1" = "$FileFromDir2" ]
then

#f file name from directory1 is match to file name of directory2 [ flage is true ]
flag=1

# short both file by time and select first file
record=`ls -lt $dir1/$FileFromDir1 $dir2/$FileFromDir2 | head -n 1`


# copy [ Dir/filename ] of selected file
filePath=`echo $record | cut -d " " -f 8`


# copy selected file to the tageted directory
cp $filePath TargetDir

fi
done

#if file name from directory1 is does NOT match to file name of directory2 [ copy to TargetDir ]
if [ $flag -eq 0 ]
then
cp $dir1/$FileFromDir1 TargetDir
fi
done

# copy rest of file from directory2 to TargetDir
for FileFromDir2 in `cat dir2.txt`
do
flag=0
for FileFromDir1 in `cat dir1.txt`
do
if [ "$FileFromDir2" = "$FileFromDir1" ]
then
flag=1
fi
done
if [ $flag -eq 0 ]
then
cp $dir2/$FileFromDir2 TargetDir
fi
done

0 comments:

Follow by Email

Total Pageviews

© BipinRupadiya.com. Powered by Blogger.