shell定期清除过期文件

背景

数据库备份文件每天生成一个,但要求只保留最近一周的备份文件,所以通过定时任务删除

过期的文件

实现方式

通过crontab定时任务,每天执行一次任务,将过期的数据文件删除

定时任务

15 0 * * * deletefiles.sh --dataPath=/opt/mysql --dateTime=7 --fileName=*.sql >> /var/log/deletefiles.log

实现文件deletefiles.sh

#!/bin/bash

#current_path=`pwd`
case "`uname`" in
    Linux)
        bin_absolute_path=$(readlink -f $(dirname $0))
        ;;
    *)
        bin_absolute_path=`cd $(dirname $0);pwd`
        ;;
esac

getopt_cmd=$(getopt -n $(basename $0) -o u: --long dataPath:,dateTime:,fileName: -- "$@")
[ $? -ne 0 ] && exit 1
eval set -- "$getopt_cmd"

userName=`whoami`

if [  $userName == "root" ];then
   echo -e "\e[33minstall check...\e[0m" 
else 
   echo -e "\e[33muser is $userName,you should be root\e[0m" 
   exit
fi

PRGDIR=`dirname "$PRG"`
HOME_PATH=$(cd $(dirname $0)/ && pwd)

data_path="${HOME_PATH}"
date_time="7"

function deletefiles(){
  if [ -z "${data_file}" ];then
    usage
  fi
  local currentDate=`date +%s`
  echo "current date is:" $currentDate
  for file in `find ${data_path} -name ${data_file}`;do
    local name=$file
    local modifyDate=$(stat -c %Y $file)
    local existTime=$[$currentDate-$modifyDate]
    local existTime=$[$existTime/86400]
    if [ $existTime -gt $date_time ];then
      echo "file:" $name "modify Date:" $modifyDate + "Exist time:" $existTime + "Delete:yes"
      rm -rf $file
    else
      echo "file:" $name "modify Date:" $modifyDate + "Exist time:" $existTime + "Delete:no"
    fi
  done
}

function create(){

  echo -e "\033[33m...\033[0m"

}

function usage(){

echo "usage: tools [--options <string>] [show]
   -u                          用户默认为当前登录用户
   
   --dataPath  <string>        数据文件路径,默认当前路径
   --dateTime  <string>        指定日期,默认7d
   --fileName  <string>        指定文件名称,例: --fileName=abc*.zip

   deletefiles                 删除指定日期前文件,例: deletefiles --dataPath=/opt --dateTime=7 --fileName=aa*.zip

"
exit
}

function starts(){

  case "$1" in 
    deletefiles) deletefiles ;; 
    *) usage ;;
  esac

}

function init(){
  while [ -n "$1" ];do
    case "$1" in 
      -u) userName="$2" ;shift ;;
      --dataPath)  data_path="$2" ;shift ;;
      --dateTime)  date_time="$2"  ;shift ;;
      --fileName)  data_file="$2"  ;shift ;;
      *) starts $2 ;shift ;;
    esac
  shift
  done
}

if [ "$#" -gt 1 ];then 
  init $*
else 
  usage 
fi
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值