使用shell脚本+Cron任务自动执行postgres数据库备份

2022/7/27 2:22:51

本文主要是介绍使用shell脚本+Cron任务自动执行postgres数据库备份,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

思路:先创建一个shell脚本,用于备份pgsql数据库,再使用Cron任务,根据自己需求设置定时任务。

环境:centos7+postgres12.0

一、创建一个根据日期来定义备份文件名的脚本

1. 创建db_backup.sh文件

touch db_backup.sh

2. 赋予777权限

chmod -R 777 db_backup.sh

二、对db_backup.sh文件进行编写脚本

编辑db_backup.sh

#!/bin/bash

#备份路径
path=/home/postgres/db_back;

#创建备份路径文件
if [ ! -d "$path" ];then
   mkdir -p $path;
fi

#获取备份日期时间
cur_time=$(date '+%Y-%m-%d-%H-%M-%S')

#db数据库名称
dbname=oyzData_CivilAirDefence_NeiMengGu_Xilinguolemeng_postgresql

#执行备份命令
/usr/local/pgsql/bin/pg_dump -h 127.0.0.1 -U postgres -p 5432 -E UTF8 -f ${path}/backup_$cur_time.sql ${dbname} --inserts

三、编辑crontab以创建新的cron任务

1、编辑cron定时任务

crontab -e

2、每周六凌晨五点备份(具体备份时间以自己公司要求为准)

00  5  *  *  6 /usr/local/sbin/db_backup.sh

四、重启cron定时任务

systemctl restart crond

五、备份的数据就保存在/home/postgres/db_back目录下。

六、使用定时任务执行db_backup.sh备份脚本备份结果为空

1、用crontab自动备份postgresql的时候导出总是为空,原因是corn的环境变量中没有pg_dump,所以用crontab执行pg_dump的时候要加上绝对路径,如:/usr/local/pgsql/bin/pg_dump xxxxxxx这样就可以了。

2、如果系统中配置了mysql的环境变量,可以在脚本的开头添加一行:

#!/bin/bash
source /etc/profile






这篇关于使用shell脚本+Cron任务自动执行postgres数据库备份的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程