下面这个是脚本
postgreSQL_user="postgres" #postgreSQL备份用户 postgreSQL_host="IP地址" #数据库地址 postgreSQL_port="5432" #端口号 postgreSQL_charset="utf8" #postgreSQL编码 backup_db_arr=("数据库名") #要备份的数据库名称,多个用空格分开隔开 如("db1" "db2" "db3") backup_location=/opt/b #备份数据存放位置,末尾请不要带"/",此项可以保持默认,程序会自动创建文件夹 expire_backup_delete="ON" #是否开启过期备份删除 ON为开启 OFF为关闭 expire_days=3 #过期时间天数 默认为三天,此项只有在expire_backup_delete开启时有效 backup_time=`date +%Y%m%d%H%M` #定义备份详细时间 backup_Ymd=`date +%Y-%m-%d` #定义备份目录中的年月日时间 backup_3ago=`date -d '3 days ago' +%Y-%m-%d` #3天之前的日期 backup_dir=$backup_location/$backup_Ymd #备份文件夹全路径 welcome_msg="Welcome to use PostgreSQL backup tools!" #欢迎语 postgreSQL_ps=`ps -ef |grep PostgreSQL|wc -l` # postgreSQL_listen=`netstat -an |grep LISTEN |grep $postgreSQL_port|wc -l` if [ [$postgreSQL_ps == 0] -o [$postgreSQL_listen == 0] ]; then echo "ERROR:postgreSQL is not running! backup stop!" exit else echo $welcome_msg fi psql -h$postgreSQL_host -p$postgreSQL_port -U$postgreSQL_user <<end end flag=`echo $?` if [ $flag != "0" ]; then echo "ERROR:Can't connect postgreSQL server! backup stop!" exit else echo "postgreSQL connect ok! 开始备份 Please wait......" # 判断有没有定义备份的数据库,如果定义则开始备份,否则退出备份 if [ "$backup_db_arr" != "" ];then #dbnames=$(cut -d ',' -f1-5 $backup_database) #echo "arr is (${backup_db_arr[@]})" for dbname in ${backup_db_arr[@]} do echo "database $dbname backup start..." `mkdir -p $backup_dir` `pg_dump -h$postgreSQL_host -p$postgreSQL_port -U$postgreSQL_user -d$dbname | gzip > $backup_dir/$dbname-$backup_time.sql.gz` flag=`echo $?` if [ $flag == "0" ];then echo "database $dbname success backup to $backup_dir/$dbname-$backup_time.sql.gz" else echo "database $dbname backup fail!" fi done else echo "ERROR:No database to backup! backup stop" exit fi # 如果开启了删除过期备份,则进行删除操作 if [ "$expire_backup_delete" == "ON" -a "$backup_location" != "" ];then #`find $backup_location/ -type d -o -type f -ctime +$expire_days -exec rm -rf {} \;` `find $backup_location/ -type d -mtime +$expire_days | xargs rm -rf` echo "Expired backup data delete complete!" fi echo "All database backup success! Thank you! 数据库备份完成!!!!!" exit fi
在使用此脚本的时候有可能遇到错误,不要慌张,用了此命令一定让你健步如飞
sed -i 's/\r//' 文件名.sh
然后再执行这条命令
sh 文件名.sh
希望能帮到你