Sunday 1 October 2017

unix - How can I script making a backup of recently modified files in Bash?


I have written this backup script that looks in a file and copies recent files into a folder.


#!/usr/bin/bash

# the number of days to do the backup for.
days=2;

# the files to backup.
location[0]='/opt/location'

# the location to copy the file to
copyLocation='/users/me/Backup/firstBackupScriptTry'

# preform the back up
for i in ${location[*]}
do
find $i \! -name '*.class' -mtime -$days \! -type d -exec cp {} $copyLocation \;
done

It works but it is not that useful.


I would prefer the script to preserve the directory structure when it copies. Ie I would like it to do: cp -r from to but only copy the recent files.



Answer



A way would be to modify the file names that you get when running find. So in your loop, having a matched file name in $filename you shall:



  1. In $filename, replace the leading $i with nothing

  2. find out the $dir_name in the result of 1 by using dirname

  3. append a trailing $copyLocation to $dirname and use it as argument for mkdir -p to create missing directories

  4. copy $filename to "$copyLocation/$dirname"


I'm also going to suggest yet another file sync alternative: unison. It is easier to use than rsync.


No comments:

Post a Comment

Where does Skype save my contact's avatars in Linux?

I'm using Skype on Linux. Where can I find images cached by skype of my contact's avatars? Answer I wanted to get those Skype avat...