使用linux命令删除X天前的文件

转载自: https://www.vionblog.com/linux-delete-files-older-than-x-days/

This is a very simple tutorial how to find and delete files older than X days. I needed this for a project where i collected some images and after a while they took too much space.

With this you will be able with the Linux find command to find your JPG files older then 30 days and then execute rm command on them.

Delete command

find /path/to/files/ -type f -name '*.jpg' -mtime +30 -exec rm {} \;

Explanation

  • First part is the path where your files are located. Don’t use wildcard * if you have a lot of files because you will get Argument list too long error.
  • Second part -type is the file type f stands for files
  • Third part -name is limiting *,jpg files
  • Fourth part -mtime gets how many days the files older then will be listed. +30 is for files older then 30 days.
  • Fifth part -exec executes a command. In this case rm is the command, {} gets the filelist and \; closes the command

Move command

find /path/to/files/ -type f -name '*.jpg' -mtime +30 -exec mv {} /path/to/archive/ \;

Explanation

  • First part is the path where your files are located. Don’t use wildcard * if you have a lot of files because you will get Argument list too long error.
  • Second part -type is the file type f stands for files
  • Third part -name is limiting *,jpg files
  • Fourth part -mtime gets how many days the files older then will be listed. +30 is for files older then 30 days.
  • Fifth part -exec executes a command. In this case mv is the command, {} gets the filelist, path where to move the files and \; closes the command

Combine commands

Now we can combine this two command to archive the images older than 10 days and delete them from the archive folder if they are older then 30 days.

We are going to create a shell script that will do that and we can run it with a crontab.

#!/bin/bash
/usr/bin/find /path/to/files/ -type f -name '*.jpg' -mtime +10 -exec mv {} /path/to/archive/ \;
/usr/bin/find /path/to/archive/ -type f -name '*.jpg' -mtime +30 -exec rm {} \;

This command should work on most of the Linux distributions.

最终我的crontab语句如下:(每天零点定时删除/data/master-template/tmpImages/目录下的5天前所有文件)

-type f 的意思是文件类型为file

+5 的意思是 5*24 hours 久的

0 0 * * * find /data/master-template/tmpImages/* -mtime +5 -type f -delete

于是我crontab -e,去编辑crontab,在末尾加上了上述语句。(可以通过crontab -l 查看所有当前的定时任务)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值