postgres数据库备份脚本
时间:2019-08-20 17:58:28 来源:igfitidea点击:
Postgresql是一个开源的对象关系数据库系统,它同样被广泛应用于mysql数据库系统。
如果你熟悉mysql,你一定要知道,你可以用一行代码传递mysql用户的密码,
例如'mysql-u root-p password`。但在postgresql中并不是这样。
解决方案:为了克服postgres用户密码的传递问题,我们可以在脚本中临时设置环境变量 PGPASSWORD,备份后再取消设置环境变量。
脚本测试环境postgresql 9.1版
如何实现postgres数据库备份脚本
使用postgres用户登录
root@theitroad:~# root@theitroad:~# su -l postgres postgres@theitroad:~$
检查用户的主目录路径
postgres@theitroad:~$ echo $HOME /var/lib/postgresql postgres@theitroad:~$
创建一个名为 dbbackup的目录,将数据库备份保存到本地系统。
postgres@theitroad:~$ whoami postgres postgres@theitroad:~$ mkdir ~/dbbackup postgres@theitroad:~$ postgres@theitroad:~$ ls -ld dbbackup/ drwxrwxr-x 2 postgres postgres 4096 Oct 20 09:25 dbbackup/ postgres@theitroad:~$ postgres@theitroad:~$ pwd /var/lib/postgresql postgres@theitroad:~$
创建备份脚本dbbackupscript.sh
vi ~/dbbackupscript.sh
#!/bin/bash
# Author: Hyman
# Date: 10-01-2014
# Desc: Single Database postgres backup script
# We are using username postgres here which is similar to mysql root user
#
#
DATABASE=test
FILE=$DATABASE-`date +%F-%H%M%S`.sql
export PGPASSWORD=postgress_password
## backup command
pg_dump -U postgres $DATABASE > ~/dbbackup/$FILE
## compressing the backup file
gzip ~/dbbackup/$FILE
## Removing export
unset PGPASSWORD
FILESIZE=$( du -sh ~/dbbackup/$FILE.gz )
## Using condition
if [ ! -f ~/db-backup/$FILE.gz ]; then
echo "$FILE.gz File not found!" | mail -s "postgres database name $DATABASE backup is failed" [email protected]
else
echo "$FILE.gz File found, Actual size after compression is $FILESIZE " | mail -s "postgres database name $DATABASE backup is completed" [email protected]
fi
记得修改PGPASSWORD和DATABASE的值。
修改脚本的权限
chmod 750 dbbackupscript.sh
运行脚本:
$ sh ~/dbbackupscript.sh $ ls -l ~/dbbackup
设置定时任务
crontab -u postgres -e 01 00 * * * sh ~/dbbackupscript.sh

