12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485 |
- #!/bin/bash
- # ██╗ ██╗ ██████╗ ██╗ ██╗ ████████╗ ██████╗ ██╗ ██╗███████╗███████╗
- # ██║ ██║██╔═══██╗██║ ██║ ╚══██╔══╝██╔═══██╗ ██║ ██║██╔════╝██╔════╝
- # ███████║██║ ██║██║ █╗ ██║ ██║ ██║ ██║ ██║ ██║███████╗█████╗
- # ██╔══██║██║ ██║██║███╗██║ ██║ ██║ ██║ ██║ ██║╚════██║██╔══╝
- # ██║ ██║╚██████╔╝╚███╔███╔╝ ██║ ╚██████╔╝ ╚██████╔╝███████║███████╗
- #╚═╝ ╚═╝ ╚═════╝ ╚══╝╚══╝ ╚═╝ ╚═════╝ ╚═════╝ ╚══════╝╚══════╝
- #
- # 1. set exec perms
- # chmod +x pg_backup.sh
- # 2. run .pg_backup db_01 db_02 ... db_n
- #
- set -e
- # CONTAINER="database"
- CONTAINER="postgres"
- # DB_USER="odoo"
- DB_USER="postgres"
- DATE=$(date +%Y%m%d)
- TIME=$(date +%H%M%S)
- DAYS_TO_KEEP=7
- # BACKUP_PATH="/mnt/backup/local"
- # CLONE_PATH="/mnt/backup/nfs"
- BKP_PATH="/home/robert/test_pg_backup"
- SYNC_PATH="/home/robert/test_sync_backup"
- TMP_PATH="."
- # perform database backup if docker exist
- perform_backups()
- {
- if [ ! -x "$(command -v docker)" ]; then
- echo "cannot perform backup"
- exit 1
- fi
- local BKP_TODAY_PATH=$(printf "%s/backup_%s" "$BKP_PATH" "$DATE")
- if [ ! -d "$BKP_TODAY_PATH" ]; then
- mkdir "$BKP_TODAY_PATH"
- fi
- for DB_NAME in $@; do
- local TMP_FILE=$(printf "%s/%s_%s.tar" "$TMP_PATH" "$DB_NAME" "$TIME")
- docker exec $CONTAINER pg_dump -U $DB_USER -d $DB_NAME -F tar -C -b -c -f $TMP_FILE
- docker cp $CONTAINER:$TMP_FILE $BKP_TODAY_PATH
- docker exec $CONTAINER rm $TMP_FILE
- done
- }
- # delete old backups
- delete_old_backups()
- {
- find $1 -maxdepth 1 -type d -name "backup_*" -mtime +$2 -exec rm -rf '{}' ';'
- }
- # sync two backup paths
- local_sync_backups_path()
- {
- if [ ! -x "$(command -v rsync)" ]; then
- echo "cannot sync backups path"
- exit 1
- fi
- rsync -arz $1 $2
- }
- # sync two backup paths remotely
- remote_sync_backups_path()
- {
- if [ ! -x "$(command -v rsync)" ]; then
- echo "cannot sync backups path"
- exit 1
- fi
- rsync -arz "ssh -p $1" "$2@$3:$4" $5
- }
- perform_backups $@
- delete_old_backups $BKP_PATH $DAYS_TO_KEEP
- sync_local_backups_path $BKP_PATH $SYNC_PATH
- exit 0
|