Simple file backup script for sysadmins

A friend of mine, Tony Krch, wrote this nearly ten years ago and I’ve used it ever since.  When ever I edit a system config file, like /etc/named.conf, I first do

cd /etc
backup resolv.conf

Then I edit.  The backup script makes a copy using “cp -a” of the file, puts it in a sub-directory called backups and appends a date-time extension to the file.  When I need to revert or see what I’ve done, I can vimdiff the current to anyone of the backups.

Now, there are “better” ways to manage your system configs – like using cfengine, puppet or even just rcs, cvs, svn or one of the other SCM systems.  I like this script better though.  Simple, quick, easy.  Here it is, with many thanks to Tony:

#!/bin/bash

# Make backup of system file(s) in directory ./backups
# Tony Krch - 03/24/00 - tony@krch.net
# useage: backup 
# user must cd to directory files to back up reside in prior to making backup

# let's make sure we were invoked correctly
if  echo $@ | grep "/" > /dev/null
  then
    echo "usage: please cd to dir containing files to back up"
    exit 1
fi

# let's see if we already have our backups dir, if not, create it.
if [ -f "./backups" ]; then
  echo "Can't create dir ./backups, file by that name exists"
  exit 1
elif [ ! -d "./backups" ]; then
  mkdir ./backups
    if [ ! $? ]; then
        echo "*** ERROR: couldn't create ./backups dir"
        exit 1
    fi
elif [ ! -w ./backups ]; then
  echo "*** ERROR: No write access to backups dir"
  exit 1
fi

# everything looks reasonable, let's go ahead and do the real work.

DATESTR=$(date +%Y%m%d)         #format the date for use in the file name
STATUS=0                        #assume sucessful execution

# process ARG list
if
  [ $# -lt 1 ]; then
    echo "usage: backup  [] ..."
    exit 1
fi

#back up the files
for ARG
  do
    if [ ! -f "$ARG" ]; then
        echo "*** backup: $ARG: not found"
        STATUS=1
        continue
    fi
    let SEQ=1
    while [ "$SEQ" -lt 100 ]
      do
        if [ $SEQ -lt 10 ]; then
          SEQSTR="0$SEQ"
        else
          SEQSTR=$SEQ
        fi
        if [ ! -f "./backups/$ARG.$DATESTR$SEQSTR" ]; then
          cp -p $ARG ./backups/$ARG.$DATESTR$SEQSTR
          echo "copied $ARG to ./backups/$ARG.$DATESTR$SEQSTR"
          break
        elif [ "$SEQ" = 99 ]; then
          echo "*** ERROR: too many copies of $ARG, no backup made"
          STATUS=1
          break
        else
          let SEQ=$SEQ+1
        fi
      done
  done
exit $STATUS

Leave a Reply

You must be logged in to post a comment.