PostgreSQL Database Backup Tutorial
for this, please create a shell script with the name backup_script.sh (type vim backup_script.sh)#!/bin/bash
# Location to place backups.
backup_dir="/home/globalway/Dropbox/"
#String to append to the name of the backup files
backup_date=`date +%d-%m-%Y`
#Numbers of days you want to keep copie of your databases
number_of_days=30
databases=`PGPASSWORD="xxxxx" psql -l -t -U 'xxxx' | cut -d'|' -f1 | sed -e 's/ //g' -e '/^$/d'`
for i in $databases; do
if [ "$i" == "prpo_production" ]; then
echo Dumping $i to $backup_dir$i\_$backup_date
PGPASSWORD="xxxxx" pg_dump -Fc -U 'xxxx' $i > $backup_dir$i\_$backup_date
fi
done
find $backup_dir -type f -prune -mtime +$number_of_days -exec rm -f {} \;
make sure you customize and replace the bold text. the script above will perform / save the last 30 days backup only.
backup_dir : where the database file will be stored
PGPASSWORD : database user password -U : database username used
number_of_days : is filled freely, the default is 30 days which means the script will backup the last 30 days only, the rest will be deleted automatically..
after backup_script.sh is saved in /root/backup_script.sh
the next thing is to create a cronjob so that the backup file is always running every day.
type crontab -e and enter the syntax below0 18 * * * /root/backup_script.sh >> /root/cron.log 2>&1
then backup_script.sh will run every day at 6pm. for the log can be seen in /root/cron.log
Tutorial Backup Database MySQL / MariaDB
please create a shell script with the name backup_script.sh (type vim backup_script.sh)
#!/bin/sh
now="$(date +'%d_%m_%Y_%H_%M_%S')"
filename="db_backup_$now".gz
backupfolder="/root/database"
fullpathbackupfile="$backupfolder/$filename"
logfile="$backupfolder/"backup_log_"$(date +'%Y_%m')".txt
echo "mysqldump started at $(date +'%d-%m-%Y %H:%M:%S')" >> "$logfile"
mysqldump --user=root --password=xxxx --default-character-set=utf8 nama_database | gzip > "$fullpathbackupfile"
echo "mysqldump finished at $(date +'%d-%m-%Y %H:%M:%S')" >> "$logfile"
chown root "$fullpathbackupfile"
chown root "$logfile"
echo "file permission changed" >> "$logfile"
find "$backupfolder" -name db_backup_* -mtime +8 -exec rm {} \;
echo "old files deleted" >> "$logfile"
echo "operation finished at $(date +'%d-%m-%Y %H:%M:%S')" >> "$logfile"
echo "*****************" >> "$logfile"
exit 0
bold writing please adjust to the conditions of each vps including the user and password.The above script will keep the database covered for about 10 days back, the rest will be deleted automatically.
put backup_script.sh in /root/backup_script.sh
Make a cronjob to run the script above every day by typing crontab -e and entering the syntax below:0 0 * * * /root/backup_script.sh >> /root/backup_database.log 2>&1
then the script will be run every day at 00:00, for logs can be seen in /root/backup_database.log