这是一段自动备份nginx/mysql日志的shell脚本,该脚本自动检测主机上所部署的服务并按日期分割其日志,然后打包并备份至指定的目录。
#!/bin/bash # 将脚本赋予执行权限 chmod +x # 添加一个定时任务 crontab -e # 指定脚本执行时间 0 0 * * * # 备份目录 backup_dir="/opt/backup/log/" # 备份日志 backup_log="${backup_dir}backup.log" # 源始日志保留时长 log_period="+180" # 备份日志保留时长 tar_period="+180" # 获取前一天的日期 lastday=`date -d "1 days ago" +%Y-%m-%d` BACKUP_WEB_LOG () { # 备份nginx日志 app_name="nginx" check_ps=`ps -ef | grep -v grep | grep -i "${app_name}"` # 如果没有部署nginx则退出该函数 [ -z "${check_ps}" ] && return 1 # 源始日志路径和列表 log_path="/mnt/sdb/nginx/logs/" log_list=("access" "error") if [ -d ${log_path} ] then cd ${log_path} for log in ${log_list[@]} do # 源始日志名称 src_name="${log}.log" # 日志备份格式 pre_name="${app_name}_${log}_${lastday}" log_name="${pre_name}.log" tar_name="${pre_name}.tar.gz" echo "开始备份${log_name}" >> ${backup_log} # 备份日志 mv ${src_name} ${log_name} tar -zcf ${tar_name} ${log_name} mv ${tar_name} ${backup_dir} echo "成功备份${log_name}" >> ${backup_log} # 删除过期的备份日志 find . -mtime ${log_period} -name ${app_name}_${log}_* -exec rm -f {} \; echo "成功删除${app_name}_${log}的过期日志" >> ${backup_log} done fi } BACKUP_MYSQL_LOG () { # 备份mysql日志 app_name="mysqld" check_ps=`ps -ef | grep -v grep | grep -i "${app_name}"` [ -z "${check_ps}" ] && return 1 log_path="/var/log/mysql/" src_name="${app_name}.log" pre_name="${app_name}_${lastday}" log_name="${pre_name}.log" tar_name="${pre_name}.tar.gz" if [ -d ${log_path} ] then cd ${log_path} echo "开始备份${log_name}" >> ${backup_log} mv ${src_name} ${log_name} tar -zcf ${tar_name} ${log_name} mv ${tar_name} ${backup_dir} echo "成功备份${log_name}" >> ${backup_log} find . -mtime ${log_period} -name ${app_name}_ -exec rm -f {} \; echo "成功删除${app_name}的过期日志" >> ${backup_log} fi } # BEGIN_BACKUP # 如果备份目录不存在则创建 [ ! -d ${backup_dir} ] && mkdir -p ${backup_dir} echo ">>>>> `date "+%Y-%m-%d %H:%M:%S"` <<<<<" >> ${backup_log} BACKUP_WEB_LOG BACKUP_MYSQL_LOG echo -e "开始删除备份目录中的过期日志\n" >> ${backup_log} cd ${backup_dir} find . -mtime ${tar_period} -name *.tar.gz -exec rm -f {} \;
原创文章禁止转载:技术学堂 » 自动备份nginx/mysql日志的shell脚本