Linux simple backup script tutorial

  

First, write the script as follows: create a backup directory

# mkdir /backup

Edit backup script

# vi /backup/bak .sh

script reads as follows:

# /bin /bash ## uses:! mysql backup data, delete the data of #### k days ago: Barlow #### final Revision: 2013-03-16####Set backup retention days KK=7#Get current date TODAY=`date '+%Y%m%d'`#Get K days before date KDAY=`date -d " ;$TODAY - $K day" '+%Y%m%d'`#Create a backup subdirectory mkdir -p /backup/$1# to back up and write the result to the log tar zcvf /backup/$1/$TODAY. Tar.gz $1 >/dev/null 2>/backup/$1/$TODAY.bak.log#Judge whether an error occurred and write the execution to the log if [ $? -eq 0 ]thenecho "$1 $TODAY backup Is successful!" >> /backup/$1/$TODAY.bak.logelseecho "$1 $TODAY backup is error!" >> /backup/$1/$TODAY.bak.logfi

#Delete expired backup if [ -d "/backup/$1/$KDAY.tar.gz" ]rm -rf /backup/$1/$KDAY.tar.gzelseecho "The $KDAY.tar.gz is not Exist!&quo t; >> /backup/$1/$TODAY.bak.logfiexit

Note: $1 indicates the first parameter followed by the script execution, which is the directory we need to back up $? The previous command execution status, if the return result is 0, the execution is normal, otherwise it is not normal

Second, the configuration plan task: establish a backup task plan, such as backup mysql directory, every day at 3 am, as follows :

#vim /etc/crontab0 3 * * * root /backup/bak.sh /var/lib/mysql

Note: 1. Shell scripts and scheduled tasks are written as described above , you can use the same script for many backups, where /var/lib/mysql is $1 in the backup script. 2. General system-level scheduled tasks are put into /etc/crontab, user-level scheduled tasks use crontab -e edit.

Three, restart the service to make the scheduled task effective. Remember to restart the crond service and set it to self-start:

#service crond restart stop crond: [OK] Starting crond: [ ,null,null,3],OK]#chkconfig crond on

Copyright © Windows knowledge All Rights Reserved