Shell – Copy whole folder from source to destination and remove extra files or folder from destination

file-copylinuxshell-script

I need to copy all files and directory from source let's say /var/www/html/test/ to destination /var/www/html/test2/. Destination can already have extra files and folders which i need to remove after copying the files from source.

I cannot delete everything from destination before copying it.

UPDATE

I tried following :

1) Copied the file from source to destination using cpcommand

cp -R source destination

which working fine.

2) I tried to iterate over all the files in destination file to check if the file is exist in source. If not remove the file from destination

for file in /var/www/html/test2/*; 
  do filestr=`basename $file`;echo $file; 
  if [ `ls /var/www/test1/ | grep -c $filestr` -eq 0 ]; 
 then rm $file; fi; 
done;

which working fine for the root files in the destination only.

Need to find out how to recursively check all file and directory matching with source or not.

Best Answer

#!/bin/bash

SOURCE="/var/www/html/test/"
DESTINATION="/var/www/html/test2/"

cp -pRu "$SOURCE*" "$DESTINATION"

HITSDIR=`find $DESTINATION -type d | sed -e 's|'$DESTINATION'\(.*\)|\1|g'`

for i in $HITSDIR; do
if [ -e $SOURCE$i ]; then
echo Yes $SOURCE$i exists
else
echo Nope delete $DESTINATION$i.
#rm -r $DESTINATION$i
fi
done

HITSFILES=`find $DESTINATION -type f | sed -e 's|'$DESTINATION'\(.*\)|\1|g'`

for i in $HITSFILES; do
if [ -e $SOURCE$i ]; then
echo Yes $SOURCE$i exists
else
echo Nope delete $DESTINATION$i.
#rm $DESTINATION$i
fi
done

This should do what you want, just uncomment the rm once you did a dry run.

Related Question