#!/bin/bash
# 检查是否以 root 用户身份运行
if [ "$EUID" -ne 0 ]; then
echo "Please run as root"
exit
fi
# 配置参数
ORACLE_SID=db19c # 替换为你的数据库实例名称
ORACLE_HOME=/u01/app/oracle/product/19.10.0/db_home/db_1 # Oracle Home 路径
BACKUP_DIR=/data/ora_backup # 备份文件存放目录
TIMESTAMP=$(date +%Y%m%d_%H%M%S) # 时间戳
LOG_FILE=${BACKUP_DIR}/oracle_backup_0_${TIMESTAMP}.log # 日志文件路径
# 切换到 oracle 用户并执行备份命令
su - oracle -c "
export ORACLE_SID=${ORACLE_SID}
export ORACLE_HOME=${ORACLE_HOME}
export PATH=\$ORACLE_HOME/bin:\$PATH
# 创建备份目录(如果不存在)
mkdir -p ${BACKUP_DIR}
# 启动 RMAN 并执行备份
rman target / <<EOR > ${LOG_FILE} 2>&1
RUN {
# 设置备份保留策略(可选)
CONFIGURE RETENTION POLICY TO RECOVERY WINDOW OF 7 DAYS;
# 删除过期备份(可选)
CROSSCHECK ARCHIVELOG ALL;
DELETE NOPROMPT OBSOLETE;
# 分配通道
ALLOCATE CHANNEL c1 DEVICE TYPE DISK;
ALLOCATE CHANNEL c2 DEVICE TYPE DISK;
ALLOCATE CHANNEL c3 DEVICE TYPE DISK;
ALLOCATE CHANNEL c4 DEVICE TYPE DISK;
# 备份数据库
#BACKUP DATABASE TAG 'FullDatabaseBackup' FORMAT '${BACKUP_DIR}/db_full_%d_%T_%U.bak';
# 备份数据库(Level 0 全量备份)
BACKUP INCREMENTAL LEVEL 0 DATABASE TAG 'FullDatabaseBackup' FORMAT '${BACKUP_DIR}/db_full_level_0_%d_%T_%U.bak';
# 归档当前日志以及备份
sql 'alter system archive log current ';
BACKUP ARCHIVELOG ALL TAG 'ArchiveLogBackup' FORMAT '${BACKUP_DIR}/arch_%d_%T_%U.bak';
###备份过的归档日志不再备份
#BACKUP ARCHIVELOG ALL NOT BACKED UP 1 times TAG 'ArchiveLogBackup' FORMAT '${BACKUP_DIR}/arch_%d_%T_%U.bak';
# 备份控制文件
BACKUP CURRENT CONTROLFILE TAG 'ControlFileBackup' FORMAT '${BACKUP_DIR}/crt_%d_%T_%U.bak';
# 删除已备份的归档日志(可选)
DELETE NOPROMPT ARCHIVELOG ALL BACKED UP 1 TIMES TO DEVICE TYPE DISK;
#删除3天前
#delete noprompt archivelog all completed before 'sysdate-3';
# 释放通道
RELEASE CHANNEL c1;
RELEASE CHANNEL c2;
RELEASE CHANNEL c3;
RELEASE CHANNEL c4;
}
EOR
# 检查备份是否成功
if grep -q 'Finished backup' ${LOG_FILE}; then
echo 'Backup completed successfully. Log file: ${LOG_FILE}'
else
echo 'Backup failed. Check log file for details: ${LOG_FILE}'
fi
"
# 删除超过7天的备份文件
find ${BACKUP_DIR} -type f -mtime +7 -exec rm -f {} \;