Automate SVN Export to Site w/ Bash Script

So at work we are finalizing the setup of a new server environment. The site is in PHP and the code is all in SVN. We were trying to decide what process to use to export the SVN contents to the site and that’s where I decided to learn how to write a bash script. This is my first and with some help from Jess we created the following script. The script does the following:

  • Does an info on the remote repo to get the revision number
  • Checks against local revision number which is stored in a file
  • If the revision numbers don’t match, it does a diff on both revisions and creates an list with the files that were changed
  • It then loops through each file and exports it to the site
  • Finally it stores the new revision number in the file
Feel free to use this and tweak it for your needs. This is our first draft, at this point we’ll start cleaning it up and adding more functionality but it works. Make sure to add a cron job to run it every so often and enjoy.
#!/bin/bash
# need to figure out what to do on files that need to be deleted
TARGET_DIR='/path/to/site'
REPO="svn://path.to.svn/repo"
REVISION_FILE='.revision'

echo "Getting info from remote repo"
REMOTE_VERSION=$(svn info $REPO | grep Revision)
REMOTE_VERSION=${REMOTE_VERSION: -4} # need to update to not hardcode 4 spaces back
CURRENT_VERSION=$(more $REVISION_FILE)

echo "Current Revision: $CURRENT_VERSION"
echo "Remote Revision: $REMOTE_VERSION"

if [ "$REMOTE_VERSION" -eq "$CURRENT_VERSION" ]
then
        echo "No export needed"
        exit 0
fi

echo "Getting diffs between revisions"
difflines=`svn diff --summarize -r $CURRENT_VERSION:$REMOTE_VERSION $REPO 2>&1 | awk '{print $2}'`

URL_LENGTH=${#REPO}

for i in `echo $difflines`; do
   FILENAME=${i:$URL_LENGTH}
   echo "svn export ${i} ${TARGET_DIR}${FILENAME}"
   svn export ${i} ${TARGET_DIR}${FILENAME}
done

echo "Saving revision number"
echo ${REMOTE_VERSION} > $REVISION_FILE