Feb
5
About 2 weeks ago I wrote about a little script I used to backup some of my WordPress installs automatically to Subversion. A serious problem arose with this method though, and the main reason was this line:
svn add --force *
I used this line to automatically add any new files to the repository. This was handy because often new files are created (e.g. attachments for posts in a blog), as you wouldn’t want to do this by hand every time.
This code doesn’t keep in mind deletes though. If you delete a plugin in your WordPress, SVN will miss it and start complaining. Additionally the method above overwrites SVN:Ignore settings, which means you can’t ignore certain files (e.g. cache files that change constantly).
So instead I decided to come up with a new solution: see what files are new and what are removed, and perform “svn add” and “svn remove” actions on those files. I used a bit of code from this blog to come up with a fairly good solution.
And replace it with:
svnstatus=$(svn status)
added=$(printf "$svnstatus" | sed -n 's/^[A?] *\(.*\)/\1/p')
removed=$(printf "$svnstatus" | sed -n 's/^! *\(.*\)/\1/p')
What this does is run the “svn status” command that will return a text output of all the modified files (starting with a ‘M’), added files (starting with a ‘?’) and deleted files (starting with a ‘!’). The next 2 lines do a regex to figure out the file names of the new and missing files.
Now add the following two pieces of code after the previous bit of code (and before the svn commit).
if [ "x$added" != "x" ]
then
echo adding "$added" to repository
svn add $added
fi
if [ "x$removed" != "x" ]
then
echo removing "$removed" to repository
svn remove $removed
fi
Both pieces of code use the previously regex calculated paramaters and sees if there are any files to be added or deleted. In then runs the “svn add X” and “svn add Y” commands to update the svn status. After this, a svn commit will include all new files and remove all old files from the repository. This does not remove the backup, so you always go back in time!
The “echo” commands used in these lines of code will show up on the command line, and if your cron job forwards output to an email address this can be used to check if the cron job is working correctly. If it becomes annoying, just remove them.