Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
Browse files

Backupscripts for MySQL and PostgreSQL

  • Loading branch information...
commit f6baa013d279020580f93417de4946ac241a1e19 1 parent 27d8456
@mikeplate authored
Showing with 62 additions and 0 deletions.
  1. +32 −0 mysql-backup.sh
  2. +30 −0 postgresql-backup.sh
View
32 mysql-backup.sh
@@ -0,0 +1,32 @@
+#!/bin/bash
+#
+# Backup MySQL databases.
+
+# Ensure running as root
+if [ "$(id -u)" -ne 0 ]; then
+ echo 'This script is designed to run as root'
+ exit
+fi
+if [ $HOME != '/root' ]; then
+ echo 'This script is designed to run with /root as home directory (sudo -H)'
+ exit
+fi
+
+# Ensure backup location exists
+if [ ! -d /var/backups/mysql ]; then
+ mkdir -p /var/backups/mysql
+ chown root:root /var/backups/mysql
+ chmod 700 /var/backups/mysql
+fi
+
+# Find all databases
+ALL=$(mysql -Bse 'show databases')
+for DB_NAME in $ALL; do
+ if [ -f /var/backups/mysql/$DB_NAME.gz ]; then
+ cp /var/backups/mysql/$DB_NAME.gz /var/backups/mysql/$DB_NAME-2.gz
+ fi
+ mysqldump --single-transaction $DB_NAME | gzip > /var/backups/mysql/$DB_NAME.gz
+ chown root:root /var/backups/mysql/$DB_NAME.gz
+ chmod 600 /var/backups/mysql/$DB_NAME.gz
+done
+
View
30 postgresql-backup.sh
@@ -0,0 +1,30 @@
+#!/bin/bash
+#
+# Backup PostgreSQL databases.
+
+# Ensure running as root
+if [ "$(id -u)" -ne 0 ]; then
+ echo 'This script is designed to run as root'
+ exit
+fi
+
+# Ensure backup location exists
+if [ ! -d /var/backups/postgresql ]; then
+ mkdir -p /var/backups/postgresql
+ chown root:root /var/backups/postgresql
+ chmod 700 /var/backups/postgresql
+fi
+
+# Find all databases
+ALL=$(sudo -u postgres psql -Atl | grep \| | cut -d\| -f1)
+for DB_NAME in $ALL; do
+ if [ ! $DB_NAME == 'template0' ]; then
+ if [ -f /var/backups/postgresql/$DB_NAME.gz ]; then
+ cp /var/backups/postgresql/$DB_NAME.gz /var/backups/postgresql/$DB_NAME-2.gz
+ fi
+ sudo -u postgres pg_dump $DB_NAME | gzip > /var/backups/postgresql/$DB_NAME.gz
+ chown root:root /var/backups/postgresql/$DB_NAME.gz
+ chmod 600 /var/backups/postgresql/$DB_NAME.gz
+ fi
+done
+
Please sign in to comment.
Something went wrong with that request. Please try again.