Search and Copy Script

Dear All,

I would like to create a Unix script which basically searches for files which are more than 2 days old and copy only the new files to the destination. What i mean is if the destination may have most of the files, it may not have only last 2 to 3 days file.

I am able to create the script which basically search and copy which are older than 2 days but how would i check if the destination has any of the files and how would i skip them? Also is there any other better command i can use other than "cp"?

Thanks,

RR

if you have rsync available this is ideal tool - it will not re-copy the files that have been copied already
man rsync

1 Like

I agree rsync is the tool of choice, if you don't have it the following should do what you want:

SRC=/path/to/source/files
DEST=/path/to/dest/files
cd $SRC
find . -type f -mtime -2 | while read file
do
    DDIR="$DEST/$(dirname $file)"
    if [ ! -f $DEST/$file ]
    then
        [ -d "$DDIR" ] || mkdir -p $DDIR
        cp -p $file $DDIR
    fi
done
1 Like

Thanks to both of you for your help. I have the rsync installed, I am also looking at the options.

But how will I use the rsync to copy the files which is more than 2 days old? Can i use something like this

for i in ' find /path_to_find -type f -mtime -2 -exec ls {} \;' do 
begin 
  rsync $i /destination_path 
done 

let me know. I am new to scripting and please explain if I am wrong.

I guess following should be enough

 
rsync -av <source_dir> <destination_dir>

I suppose the thing is rsync manages all this for you, it examines all the files in the source directory and any that have changed, are missing (or optionally have been removed) are synced up with the destination directory.

So no need to worry about anything changed in the last x days anymore. If you have stuff in the source you want to exclude from being copied to dest you will need to use the --exclude=PATTERN or --exclude-from=FILE options of rsync.

1 Like

Thanks, I will try that option in rsync