forked from webstylr/simple-mysqlbackup
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmysqlbackup.sh
executable file
·107 lines (99 loc) · 2.63 KB
/
mysqlbackup.sh
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
#!/bin/bash
### Write log to temporary file ###
exec &> /var/log/mysql-backuplog.txt
### Defaults Setup ###
STORAGEDIR="/data/project/backup/mysql";
NOW=`date "+%s"`;
OLDESTDIR=`ls $STORAGEDIR | head -1`;
NOWDIR=`date +"%Y-%m-%d"`;
NOWFILE=`date +"%Y-%m-%d"`;
OLDEST=`date -d "$OLDESTDIR" "+%s"`;
BACKUPDIR="$STORAGEDIR/$NOWDIR";
DIFF=$(($NOW-$OLDEST));
DAYS=$(($DIFF/ (60*60*24)));
DIRLIST=`ls -lRh $BACKUPDIR`;
ROTATION="7"
GZIPCHECK=();
### Server Setup ###
MHOST="localhost";
MPORT="3306";
IGNOREDB="
information_schema
mysql
test
performance_schema
"
MYSQL=`which mysql`;
MYSQLDUMP=`which mysqldump`;
GZIP=`which gzip`;
### Create backup dir ###
if [ ! -d $BACKUPDIR ]; then
mkdir -p $BACKUPDIR
if [ "$?" = "0" ]; then
:
else
echo "Couldn't create folder. Check folder permissions and/or disk quota!"
fi
else
:
fi
### Get the list of available databases ###
DBS="$(mysql -h $MHOST -P $MPORT -Bse 'show databases')"
### Backup DBs ###
for db in $DBS
do
DUMP="yes";
if [ "$IGNOREDB" != "" ]; then
for i in $IGNOREDB
do
if [ "$db" == "$i" ]; then
DUMP="NO";
fi
done
fi
if [ "$DUMP" == "yes" ]; then
FILE="$BACKUPDIR/$NOWFILE-$db.sql.gz";
echo "BACKING UP $db";
$MYSQLDUMP --add-drop-database --opt --lock-all-tables -h $MHOST -P $MPORT $db | gzip > $FILE
if [ "$?" = "0" ]; then
gunzip -t $FILE;
if [ "$?" = "0" ]; then
GZIPCHECK+=(1);
echo `ls -alh $FILE`;
else
GZIPCHECK+=(0);
echo "Exit, gzip test failed.";
fi
else
echo "Dump of $db failed!"
fi
fi
done;
### Check if gzip test for all files was ok ###
CHECKOUTS=${#GZIPCHECK[@]};
for (( i=0;i<$CHECKOUTS;i++)); do
CHECKSUM=$(( $CHECKSUM + ${GZIPCHECK[${i}]} ));
done
### If all files check out, delete the oldest dir ###
if [ "$CHECKSUM" == "$CHECKOUTS" ]; then
echo "All files checked out ok. Deleting oldest dir.";
## Check if Rotation is true ###
if [ "$DAYS" -ge $ROTATION ]; then
rm -rf $STORAGEDIR/$OLDESTDIR;
if [ "$?" = "0" ]; then
echo "$OLDESTDIR deleted."
else
### Error message with listing of all dirs ###
echo "Couldn't delete oldest dir.";
echo "Contents of current Backup:";
echo " ";
echo $DIRLIST;
fi
else
:
fi
else
echo "Dispatching Karl, he's an Expert";
### Send mail with contents of logfile ###
mail -s "Backuplog" [email protected] < /var/log/mysql-backuplog.txt;
fi