Skip to content

Instantly share code, notes, and snippets.

@alimli
Last active October 25, 2018 14:44
Show Gist options
  • Select an option

  • Save alimli/16cfbf7f6d80c3a17ea73e92f27471ce to your computer and use it in GitHub Desktop.

Select an option

Save alimli/16cfbf7f6d80c3a17ea73e92f27471ce to your computer and use it in GitHub Desktop.
Backup PostgreSQL Database, keep Latest N Days and deletes older
#!/bin/bash
if [ -z "$1" ]; then
echo "No argument supplied"
exit 1
fi
DB=$1
CONFIG_FILE="/etc/${DB}-backup.conf"
TIMESTAMP=$(date +'%Y-%m-%d-%H-%M')
if [ -e ${CONFIG_FILE} ]; then
source ${CONFIG_FILE}
else
echo "Error: ${CONFIG_FILE} missing"
exit 1
fi
DATABASE_DUMP_OUTPUT="${BACKUP_DIR}/${DB}-database-dump-${TIMESTAMP}.dump"
DATABASE_DUMP_REMOVE="${BACKUP_DIR}/${DB}-database-dump-*.dump"
function setup() {
if [ ! -d "${BACKUP_DIR}" ]; then
echo "Creating ${BACKUP_DIR}"
mkdir -p "${BACKUP_DIR}"
fi
}
function remove_old_files() {
if [ -n "${KEEP_DAYS}" ]; then
find $1 -mtime +${KEEP_DAYS} -delete -print
fi
}
function remove_old_database_dumps() {
if [ -n "$DB_NAME" ]; then
echo "Removing old ${DB} database dumps"
remove_old_files "$DATABASE_DUMP_REMOVE"
fi
}
function dump_database() {
if [ -z "$DB_NAME" ]; then
echo "Skiping ${DB} database dump."
else
echo "Dumping ${DB} database"
# Don't pass hostname and username since we'll run this postgres user in local machine
# /usr/bin/pg_dump -Fc -U "${DB_USER}" "${DB_NAME}" -h "${DB_HOST}" > "${DATABASE_DUMP_OUTPUT}"
/usr/bin/pg_dump -Fc "${DB_NAME}" > "${DATABASE_DUMP_OUTPUT}"
echo "Created ${DATABASE_DUMP_OUTPUT}"
fi
}
function main() {
echo "Backing up ${DB}"
setup
remove_old_database_dumps
dump_database
}
main
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment