Wednesday, September 5, 2012

Shell script to backup modified files in a directory

Want to backup your files before a day's work? This script does that!

#!/bin/bash
since=${1-1}
find  -iname "*.js" -mtime -$since > temp
if [[ -s temp ]] ; then
  date=`date +%D`
  ctime=`date +%H%M%S`
  mdate=$(echo "$date" | tr '/' '_')
  date=$mdate"_"$ctime
  mkdir /home/nanda/backups/$date
  for i in `cat temp` ; do
  i=`echo ${i:2}`
  cp $i /home/nanda/backups/$date/
  done
else
  echo "No files modified since $since day(s)"
fi ;
rm temp

Save the script as backup.sh and give executable permissions to it by typing chmod +755 backup.sh as root in your terminal.

Usage: ./backup.sh {integer number of days}

The parameter to be passed is an integer which specifies to backup files that have been modified in the last so many days. Default value is one day.

This particular script is coded for javascript .js files as seen in line 2. You can modify that for different extension types.

A backup directory with writeable permissions has to be created beforehand. In this example it is /home/nanda/backups. When the script is run, a new directory is created and is named with the time and date when it was created.

Happy Backups!

No comments:

Post a Comment