您的位置:首页 > 运维架构 > Shell

linux下遍历目录和文件,删除过期天数目录或文件shell脚本

2017-06-01 15:32 891 查看
#!/bin/bash

function delete_file()
{
INTERVAL=$(($1*3600*24))
pathdir=$2/
#echo $INTERVAL
#echo $pathdir
now_timestamp=$(date -d "$(date +"%Y-%m-%d %T")" +%s)
#echo $now_timestamp
files=$(ls $pathdir)

for file in $files;
do
#file_date=$(stat $pathdir$file | grep Modify | awk '{print $2,$3}');
file_date=$( stat $pathdir$file | tail -2|head -1 | awk '{print $1,$2}'| cut -c16- )
#echo $file_date
file_timestamp=$(date -d "$file_date" +%s)
#echo $file
#echo $file_timestamp
if [ $? -ne 0 ];
then
file_path=$file
echo "delete file 0 $pathdir$file_path"
rm -rf $pathdir$file_path
continue
fi
if [ $(($now_timestamp - $file_timestamp)) -gt $INTERVAL ]
then
file_path=$file
echo "delete file 1 $pathdir$file_path"
rm -rf $pathdir$file_path
fi
done
return 0;
}

function getdir()
{
for element in `ls $2`
do
dir_or_file=$2"/"$element
if [ -d $dir_or_file ]
then
echo $dir_or_file
delete_file $1 $dir_or_file
getdir $1 $dir_or_file
else
#delete_file $2 $dir_or_file
echo "clear finished"
fi
done
return 0;
}

root_dir="."
function main()
{
getdir $1 $root_dir
ret=$?
echo "getdir run ret:$ret"
}

main $@

使用时shell输入参数删除当前目录7天前的目录或文件

./delest_images 7
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: