Last active
April 7, 2016 07:34
-
-
Save KamilLelonek/002072f79699460379224370b92cde98 to your computer and use it in GitHub Desktop.
Dumping database script
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env bash | |
DAYS_TO_KEEP=6 | |
DB_USER=postgres | |
DUMP_DIR=/var/db_dumps | |
function create_dump_dir_unless_exist() { | |
if ! mkdir -p $DUMP_DIR | |
then | |
echo "Cannot create backup directory in $DUMP_DIR" 1>&2 | |
exit 1 | |
fi | |
} | |
function dump_postgres_config() { | |
local postgres_config_file="${DUMP_DIR}/postgres.dump" | |
pg_dumpall --globals-only > $postgres_config_file | |
} | |
function dump_database_if_exists() { | |
if database_exists $1; then | |
dump $1 | |
else | |
echo "Database '$1' does not exist!" | |
fi | |
} | |
function database_exists() { | |
psql -lqt | cut -d \| -f 1 | grep -wq $1 | |
} | |
function dump() { | |
local filename=$(filename $1) | |
if ! pg_dump -U $DB_USER $1 | gzip > $filename.in_progress; then | |
echo "Failed to backup $1" 1>&2 | |
exit 1 | |
else | |
mv $filename.in_progress $filename | |
fi | |
} | |
function filename() { | |
local timestamp=$(date +\%d-\%B-\%Y) | |
local dbname=$1 | |
echo "${DUMP_DIR}/${dbname}_${timestamp}.sql.gz" | |
} | |
function remove_old_dumps() { | |
find $DUMP_DIR -maxdepth 1 -mtime +$DAYS_TO_KEEP -name $1"_*" -exec rm -rf '{}' ';' | |
} | |
function validate_arguments() { | |
if [[ $# -ne 1 ]]; then | |
echo "Please provide exactly one argument with adatabase name to dump!" | |
exit 1 | |
fi | |
} | |
function main() { | |
validate_arguments $@ | |
create_dump_dir_unless_exist | |
dump_postgres_config | |
dump_database_if_exists $1 | |
remove_old_dumps $1 | |
} | |
main $@ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment