删除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