Skip to content

Instantly share code, notes, and snippets.

@mamu7211
Last active February 16, 2016 13:03
Show Gist options
  • Save mamu7211/7dbb50863345aaadd86c to your computer and use it in GitHub Desktop.
Save mamu7211/7dbb50863345aaadd86c to your computer and use it in GitHub Desktop.
Bash script to backup a PostgreSQL database.
#!/bin/bash
BASE_DIR="/.../.../..."
DATA_DIR="$BASE_DIR/work"
ARCHIVE_DIR="$BASE_DIR/archive"
NOW=$(date +"%Y-%m-%d_%H-%M-%S")
DB_NAME='...'
DB_USER='...'
DB_DUMP_NAME="$DATA_DIR/backup-$DB_NAME-$NOW.sql"
FTP_HOST='...'
FTP_USER='...'
FTP_PASSWD='...'
FTP_TARGET_DIR="/volume1/FTP_/backups/redmine/"
# Logging functions ----------------------
# found on http://urbanautomaton.com/blog/2014/09/09/redirecting-bash-script-output-to-syslog/
readonly SCRIPT_NAME=$(basename $0)
log() {
echo "$@"
logger -p user.notice -t $SCRIPT_NAME "$@"
}
err() {
echo "$@" >&2
logger -p user.error -t $SCRIPT_NAME "$@"
}
# Dump database into file ----------------
pg_dump -U $DB_USER $DB_NAME > $DB_DUMP_NAME
if [ $? -ne 0 ]; then
err "Error while dumping database '$DB_NAME' into '$DB_DUMP_NAME'. Exiting."
exit 1
fi
# Check if FTP is up ---------------------
ping -q -c 1 $FTP_HOST
if [ $? -ne 0 ]; then
err "Server $FTP_HOST is not available, dump '$DB_DUMP_NAME' was not transfered. Exiting."
exit 2
fi
# FTP transfer ----------------------------
ftp -n $FTP_HOST << END_OF_FTP
bin
user $FTP_USER $FTP_PASSWD
prompt
lcd $DATA_DIR
cd $FTP_TARGET_DIR
mput *.sql
bye
END_OF_FTP
if [ $? -ne 0 ]; then
err "FTP_ Transfer failed."
exit 3
fi
# Local archiving ------------------------
mv $DATA_DIR/*.sql $ARCHIVE_DIR/
log "Database '$DB_NAME' was saved into '$DB_DUMP_NAME' and transfered to $FTP_HOST."
log "Done..."
exit 0
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment