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

#!/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


  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值