Saturday, May 24, 2014

How to automate backup in Unix?

Backup Using TAR
Backing up your files using tar is very simple you just type a little command.
Command = tar -cvpzf   /BackupDirectory/backupfilename.tar.gz /ImportantData/directory/path
Let’s suppose i have directory called /imp-data on root  and i want to make backup of this directory including sub directories on  different location like in /mybackupfolder.
In above example my command will be.
tar -cvpzf /mybackupfolder/backup.tar.gz    /imp-data


Command Explaination:
tar = tape archive
c =  Create
v =  Verbose mode
p = Preserving Files and Directory Permissions.
z = This will tell tar that compress the files further to reduce the size of tar file.
f =  It is allows to tar get file name.
Let’s add tar command in bash script to make this whole backup process automatic.
Here i will show you my self-created simple bash script that i am using for backing up my important data and then we will use cron job to run our whole process in background automatically.
Here is my Super Simple Backup Script :)
Create file using vi editor and paste below script.
vi /backup.sh
#!/bin/bash
#Purpose = Backup of Important Data
#Created on 17-1-2012
#Author = Hafiz Haider
#Version 1.0
#START

TIME=`date +"%b-%d-%y"`             # This Command will add date in Backup File Name.
FILENAME="backup-$TIME.tar.gz"      # Here i define Backup file name format.
SRCDIR="/imp-data"                  # Location of Important Data Directory (Source of backup).
DESDIR="/mybackupfolder"            # Destination of backup file.
tar -cpzf $DESDIR/$FILENAME $SRCDIR

#END
This Script will make backup of /imp-data directory and save it into a single compressed file on /mybackupfolder Directory.
Linux Backup :


Now i will show you how to schedule our backup process. In Linux we use cron jobs in order to schedule task.
For setting up cron jobs we use crontab -e command in shell, this command basically says we are going to edit our cron jobs file. If you run first time crontab -e command then it will ask you to default text editor, you just select your favorite editor after that it will never ask you again.
crontab -e
Format of Crontab. It has 6 Parts:
Minutes    Hours     Day of Month    Month     Day of Week     Command
0 to 59       0 to 23      1 to 31               1 to 12        0 to 6                Shell Command
Let’s Suppose i want to run this backup process on every Mon and Sat  at 1:pm.
In Above Condition my Crontab file should be like this.
crontab -e
#   Minutes    Hours      Day of Month       Month    Day of Week    Command

      01        13               *             *        1,6          /bin/bash /backup.sh
That’s All…

No comments:

Post a Comment