#! /Bin/bashPATH =/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin: /usr/local/sbinexportPATH # Database username dbuser = & #39; root & #39; # database password dbpasswd = & #39; * ******* & #39; multiple databases to be backed up #! /Bin/bashPATH =/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin: /usr/local/sbinexport PATH # Database username dbuser = 'root' # database password dbpasswd = '********' the database to be backed up, separate multiple databases with spaces dbname = 'xiaohuai xiaohuai2' # backup time backtime = 'date + % Y % m % d % H % M % s' # log backup path logpath =' /home/mysqlbak '# data backup path datapath ='/home/mysqlbak '# log record header echo' "backup Time: $ {backtime }, backup database table $ {dbname} start ">$ {logpath}/log. log # formally back up the database for table in $ dbname; dosource = 'mysqldump-u $ {Dbuser}-p $ {dbpasswd }$ {table }>$ {logpath}/$ {backtime }. SQL '2 >>$ {logpath}/mysqllog. log; # The backup is successful. the following operations are performed if ["$? "= 0]; thencd $ datapath # to save hard disk space, compress the database by using tar jcf ${table}{backtime=.tar.bz2 $ {backtime }. SQL>/dev/null # delete the original file, leaving only the compressed file rm-f $ {datapath}/$ {backtime }. SQL # delete a backup seven days ago, that is to say, only the backup within 7 days is saved. find $ datapath-name "* .tar.bz2"-type f-mtime + 7-exec rm-rf {}\;> /dev/null 2> & 1 echo "database table $ {dbname} backed up successfully !! ">>$ {Logpath}/mysqllog. logelse # if the backup fails, perform the following operations echo" database table $ {dbname} backup failed !! ">>$ {Logpath}/mysqllog. logfidone
If the sh file is edited in win, you must use Uedit to convert it to unix format. otherwise, sh will fail to be executed,
In addition, be sure to grant the sh file the execution permission
1 |
Chmod + x/home/sh/mysqlbak. sh |
Scheduled Execution script:
Method:
1,
Execute crontab-e
Enter the following content:
______________________________________________________________________________
00 00 ***/bin/bash yourpath/mysqlbak. sh
2,
Open the automatic execution file
Vi/etc/crontab
Add the following content to etc to automatically execute the task.
00 00 *** root/mysqlbak. sh
The above two 00 *** scripts are automatically executed every morning.
Hour, day, month, and Week commands
M: minute (0-59 ). Each minute is represented by * or */1.
H: Hour (0-23 ). (0 indicates 0)
D: Day (1-31 ).
M: month (1-12 ).
D: days in a week (0 ~ 6, 0 is Sunday ).
In addition, you can directly go to the sh directory for execution during the test.
# Sh./mysqlbak. sh
Wait until the execution is complete.
# Log backup path
Logpath = '/home/mysqlbak'
There are no backup files in this directory. If yes, sh is successfully executed and there are no errors.