linux命令删除指定天数之前的文件

删除5天前的文件(非文件)

#为了在/var/logs目录中查找更改时间在 5日以前的文件(非文件夹)并删除它们
$ find /var/logs -type f -mtime +5 -exec rm {} ;
#or
$ find /var/logs -type f -mtime +5 | xargs rm -rf

删除5天前的文件夹及其内部文件

#如要要删除文件夹用如下形式:
$ find /var/logs -type d -mtime +5 -exec rm -rf {} ;
#or
$ find /var/logs -type d -mtime +5 | xargs rm -rf

删除5天前的所有文件(包含文件夹)

#如要要删除文件夹以及文件用如下形式:
$ find /var/logs -type f,d -mtime +5 -exec rm -rf {} ;
#or
$ find /var/logs -type f,d -mtime +5 | xargs rm -rf

案例

##下面的例子在/apps/audit目录下查找所有用户具有读、写和执行权限的文件,并收回相应的写权限:
$ find /apps/audit -perm -7 -print | xargs chmod o-w

##下面的例子在/var/logs目录中查找更改时间在 5日以前的文件文件,且名称中包含sha或者shb的文件夹
$ find /var/logs -type d -mtime +5 -name *.sh[ab] | xargs rm -rf

shell脚本 shell_find_&_del_days_file.sh

#!/bin/bash

#remove-file: check whether if dir exist or not, if exist then remove all files in that directory which before given days.
echo "
please enter the directory which you want to remove:
"
echo "
pay attention: the input pattern must like:
	- windows os: /cygdrive/C/Temp/file_dir [days]
	- Linux os: [your_path] [days]
"

echo -n "Enter a directory and days->"
read given_path given_day

default_day=30
if [[ -d $given_path ]]; then
	if cd $given_path; then
		if [[ $given_day =~ ^[0-9]+$ ]]; then
			echo "you want to delete files in '$given_path'"
			echo "you want to delete files before '$given_day' days"
			find $given_path -type f -mtime +${given_day} | xargs rm -rf
			#find $given_path -type d -mtime +${given_day} | xargs rm -rf
			#rm -rf *
			echo "delete FILEs success"
		else
			echo "you want to delete files in '$given_path'"
			echo "you want to delete files by default $default_day days"
			find $given_path -type f -mtime +${default_day} | xargs rm -rf
			#find $given_path -type d -mtime +${default_day} | xargs rm -rf
			#rm -rf *
			echo "delete FILEs by before default 30 days success"
		fi	
	else
		echo "cannot cd to '$given_path'" >&2
		exit 1
	fi	
else
	echo "No such file directory." >&2
	exit 2
fi


  • 1
    点赞
  • 13
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

木瓜~

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值