Skip to content

Instantly share code, notes, and snippets.

@changchichung
Forked from bahodge/take_database_snapshot.sh
Last active January 16, 2023 07:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save changchichung/d6301daf4497d90ea7ce01d6640d9eeb to your computer and use it in GitHub Desktop.
Save changchichung/d6301daf4497d90ea7ce01d6640d9eeb to your computer and use it in GitHub Desktop.
Take a snapshot of your postgres database
#!/usr/bin/bash
# This script will take a snapshot of the database
# It will then gzip it
# It will save it in the 'storage' directory
# it will delete any old db snapshots > 7 days.
echo "===== Starting Snapshot ===="
# add two vars
database_name='test_db'
database_user='test_user'
formatted_date=`date +'%m%d%Y'`
# update time format
#formatted_time=`date +'%I%M%S'`
formatted_time=`date +'%H%M%S'`
# update filename format
#filename="${formatted_date}_${formatted_time}_dbexport.pgsql"
filename="${database_name}_${formatted_date}_${formatted_time}.pgsql"
# check if dest exists , if not , the create the dest folder
path="full/path/to/project/storage"
if [ -d ${path} ]
then
path=${path}
else
mkdir -p ${path}
path=${path}
fi
full_path="${path}/${filename}"
echo '====== Dumping the DB ======'
pg_dump -U ${database_username} ${database_name} > "${full_path}"
echo '===== Gzipping the DB ======'
# use pigz instead of gzip
#gzip "${full_path}"
pigz -9 "${full_path}"
echo '===== Removing Oldest Snapshot ====='
# find all the files that end with pgsql.gz and remove them if they
# are older than 7 days from when the time this script is run
find "${path}" -type f -name '*.pgsql.gz' -mtime +7 -exec rm {} \;
# update ending
echo "===== Finishing Snapshot ===="
#echo "xxxx Finishing Snapshot xxxx"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment