-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathbackup-mysql-databases.sh
executable file
·77 lines (61 loc) · 1.93 KB
/
backup-mysql-databases.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
#!/bin/bash
# ------------------------------------------------------------------------------
# Backup all MySQL/MariaDB databases; dump & compress. Overwrites older backups
# matching the same date pattern. Recommended to be scheduled with a SystemD
# service & timer.
#
# Default settings can be changed with environment variables:
# ExcludeDatabases: databases to exclude, separated with '|'
# DatePattern: +FORMAT; see man date(1)
# compress: Compress usign Gzip; true/false
#
# Author : Esa Jokinen (oh2fih)
# Home : https://github.com/oh2fih/Misc-Scripts
# ------------------------------------------------------------------------------
# Set defaults if environment variables not set.
if [[ ! -v ExcludeDatabases ]]; then
ExcludeDatabases="information_schema|performance_schema|mysql"
fi
if [[ ! -v DatePattern ]]; then
DatePattern="%d"
fi
if [[ ! -v compress ]]; then
compress=true
fi
# Check for requirements.
if ! command -v mysql > /dev/null 2>&1; then
echo "*** ERROR! This script requires mysql!"
exit 1
fi
if ! command -v mysqldump > /dev/null 2>&1; then
echo "*** ERROR! This script requires mysqldump!"
exit 1
fi
if [ "$compress" = true ]; then
if ! command -v gzip > /dev/null 2>&1; then
echo "*** WARNING! Gzip not found; skipping compression."
compress=false
fi
fi
set -e
date=$(date "+${DatePattern}")
# List existing databases not excluded.
databases=$(
mysql -N -B -e "SHOW DATABASES;" \
| grep -E -v "$ExcludeDatabases"
)
echo "Working directory: $(pwd)"
echo "Excluding databases: ${ExcludeDatabases}"
echo "Date from pattern (${DatePattern}): ${date}"
# Backup & compress.
for db in $databases; do
echo "Dumping database: ${db}"
mysqldump --databases "$db" > "${date}-${db}.sql"
if [ "$compress" = true ]; then
echo "Compressing dump: ${date}-${db}.sql"
gzip -f "${date}-${db}.sql"
else
echo "Saved: ${date}-${db}.sql"
fi
done
echo "All backups successful."