-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpostgres_backup.sh
69 lines (57 loc) · 1.84 KB
/
postgres_backup.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
#!/bin/bash
#################################################################
#
# Backup a MySQL database and compress the backup file
# https://www.postgresql.org/docs/current/app-pgdump.html
#
#################################################################
export PATH=/bin:/usr/bin:/usr/local/bin
# Full name of the weekday followed by full name of the month
# and day of the month separated by a hyphen.
today=$(date "+%A, %B-%d, %Y")
################## Update below values #########################
DATABASE_BACKUP_PATH='/path/to/destination'
DATABASE_HOST='localhost'
DATABASE_PORT='3306'
DATABASE_USER='root'
DATABASE_NAME='mydb'
#################################################################
sqlfile=${DATABASE_BACKUP_PATH}/"${today}"/${DATABASE_NAME}-"${today}".sql
zipfile=${DATABASE_BACKUP_PATH}/"${today}"/${DATABASE_NAME}-"${today}".zip
err() {
echo "[${today}]: $*" >&2
}
if ! mkdir -p ${DATABASE_BACKUP_PATH}/"${today}"
then
err "Cannot create backup directory in ${DATABASE_BACKUP_PATH}/${today}.
Go and fix it!" 1>&2
exit 1;
fi;
echo "Backup started for database ${DATABASE_NAME}"
today
echo
# if ! pg_dump -d postgresql://${DATABASE_USER}:${DATABASE_PASSWORD}@${DATABASE_HOST}:
# ${DATABASE_PORT}/${DATABASE_NAME} > "$sqlfile"
# -W Forces pg_dump to prompt for a password before connecting to a database.
# Or create a .pgpass file containing only (and set its mode to 0600):
# hostname:port:database:username:password
if ! pg_dump -h ${DATABASE_HOST} \
-U ${DATABASE_USER} \
-W ${DATABASE_NAME} \
-p ${DATABASE_PORT} > "$sqlfile"
then
err "Dump failed"
exit 1
else
if ! gzip -c "${sqlfile}" > "${zipfile}"
then
err "Compression failed"
exit 1
else
echo "Backup done:"
# Listing of files in backup destination
ls -lh ${DATABASE_BACKUP_PATH}/"${today}"
rm "$sqlfile"
fi
fi
### End of script ####