Skip to content

Instantly share code, notes, and snippets.

@jankuo
Last active August 29, 2015 14:00
Show Gist options
  • Save jankuo/11286175 to your computer and use it in GitHub Desktop.
Save jankuo/11286175 to your computer and use it in GitHub Desktop.
#!/bin/sh
#nginx pid
nginx_pid=`ps aux|grep -E 'nginx: master process' | grep -v 'grep' | awk '{print $2}'`
#日志文件存放目录
nginx_log_store_path="dir-where-log-file-place/"
#日志文件名(去除最后.log的)
nginx_log_basename="log-file-name"
#日志文件
nginx_log_file=${nginx_log_store_path}${nginx_log_basename}.log
##检测日志文件是否存在
if [ ! -r $nginx_log_file ]; then
echo `ls $nginx_log_file`
echo $nginx_log_file,"日志文件不存在!"
exit 1
fi
#日志文件备份根目录
log_backup_base_path="dir-where-log-want-to-file-place/"
#当前操作系统
darwin_os="Darwin"
cur_os=`uname -s`
if [ $cur_os = $darwin_os ];then
today_day=`date -v-1d +"%d"`
today_month=`date -v-1d +"%m"`
yesterday_month_day=`date -v-1d +"%Y/%m"`
today=`date -v-1d +"%Y%m%d"`
else
today_day=`date -d 'yesterday' +"%d"`
today_month=`date -d 'yesterday' +"%m"`
yesterday_month_day=`date -d 'yesterday' +"%Y/%m"`
today=`date -d 'yesterday' +"%Y%m%d"`
fi
log_backup_path=${log_backup_base_path}${yesterday_month_day}/
#检测日志文件备份目录是否存在
if [ ! -d $log_backup_path ]; then
mkdir -p $log_backup_path
fi
log_backup_file=${nginx_log_basename}_${today}.log
log_backup_gz_file=${nginx_log_basename}_${today}.log.tar.gz
log_backup_gz_fullfile=${log_backup_path}${log_backup_gz_file}
#如果备份日志文件存在则不备份
if [ -f $log_backup_gz_fullfile ];then
echo "日志文件已经存在"
exit 0
fi
##移动文件
mv $nginx_log_file ${log_backup_path}${log_backup_file}
##重启nginx日志
#kill -USR1 $nginx_pid
##压缩文件
cd $log_backup_path
tar zcf $log_backup_gz_file $log_backup_file
rm -rf $log_backup_file
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment