shell+crontab+flock 定时备份

mybackup.sh

db_user="root"
db_passwd="CN66law123"
db_host="127.0.0.1"
# databases which no need to restore
db_name_ignore=(\#mysql50\#backup.0 \#mysql50\#backup.1 \#mysql50\#backup.2 \#mysql50\#backup.3 
    information_schema \ 
    performance_schema  \
    sys test  )
# the directory for story your backup file.
backup_dir="/data/backup"
# date format for backup file (dd-mm-yyyy)
time="$(date +"%d-%m-%Y")"
# mysql, mysqldump and some other bin's path
MYSQL="mysql"
MYSQLDUMP="mysqldump"
MKDIR="/bin/mkdir"
RM="/bin/rm"
MV="/bin/mv"
GZIP="/bin/gzip"
# check the directory for store backup is writeable
test ! -w $backup_dir && echo "Error: $backup_dir is un-writeable." && exit 0
# the directory for story the newest backup
test ! -d "$backup_dir/backup.0/" && $MKDIR "$backup_dir/backup.0/"
# get all databases
all_db="$($MYSQL -u $db_user -h $db_host -p$db_passwd -Bse 'show databases')"
for db in $all_db
do
    if echo "${db_name_ignore[@]}" | grep -w "$db" &>/dev/null; then
        echo "ignore db : ${db}"
    else
        echo "starting backup $db";
        $MYSQLDUMP -u $db_user -h $db_host  -p$db_passwd $db | $GZIP -9 > "$backup_dir/backup.0/$time.$db.gz"
    fi
done
# delete the oldest backup
test -d "$backup_dir/backup.5/" && $RM -rf "$backup_dir/backup.5"
# rotate backup directory
# delete the oldest backup
test -d "$backup_dir/backup.3/" && $RM -rf "$backup_dir/backup.3"
# rotate backup directory
for int in 2 1 0
do
    if(test -d "$backup_dir"/backup."$int")
    then
        next_int=`expr $int + 1`
        $MV "$backup_dir"/backup."$int" "$backup_dir"/backup."$next_int"
    fi
done
exit 0;

runbackup.sh

#! /bin/bash
date=`date '+%Y-%m-%d'`
sh /data/backup/mybackup.sh >> log$date.log 2>&1

crontab -e:

30 18 * * * (flock -xn /data/backup/my.lock bash /data/backup/runbackup.sh)

其中,my.lock事先创建,flock -xn表示获取文件独占锁,如果因上次crontab任务没有执行完,那么就得不到锁,直接终止执行(-n)

为了测试flock,写了个简单的go脚本:hello

package main
import ("fmt"
    "time"
)
func main() {
        fmt.Printf("hello, world\n")
    time.Sleep(time.Duration(10)*time.Second)
        fmt.Printf("sleep over\n")

}

执行以下的命令,正常进入10秒等待:

flock -xn /home/test/flock.lock /home/test/hello

这时候再开启一个,就直接退出,并不执行。

你可能感兴趣的:(shell+crontab+flock 定时备份)