# 13.清理目录

给定一个目录,可以根据用户参数参数删除最近n天没有任何文件改变的子目录。比如:

删除/tmp目录 最近5天没有修改的子目录。 disk_clean.sh -i /tmp -d 5

更复杂的需求,可以参考命令find (opens new window)

#!/bin/bash


help(){
    # Display Help
    echo ""
    echo ""
    echo "*******************************************************************"
    echo "*"
    echo "* disk clean tools."
    echo "*"
    echo "*******************************************************************"
    echo "syntax: disk_clean.sh -i <tar.gz name> -d <time> -h"
    echo "options:"
    echo "i     the cleaned directory"
    echo "h     Print this Help."
    echo "d     in n-days, those file are never changed so these file will be deleted"

    echo ""
    echo "Example:"
    echo "  disk_clean.sh -i /opt/aispeech/taskinfo -d 5"
    echo "  disk_clean.sh -h"

    echo ""
    
    exit 0
}

log_info(){
    msg=$1
    echo "$(date '+%Y-%m-%d %H:%M:%S') [INFO] $msg"
}

# main
today=$(date '+%Y_%m_%d')
tts_local_resource=
days=
while getopts "hi:d:" option; do
    case ${option} in
        h )
            help
        ;;
		i )
            input_dir=$OPTARG
        ;;
        d )
            days=$OPTARG
        ;;
        \? )
            echo "print help information"
            help
        ;;
    esac
done

if [[ -z $input_dir ]];then
	log_info "input_dir should be non-empty"
	help
fi

if [[ ! -d $input_dir ]];then
	log_info "input_dir should be a existed directory"
	help
fi

if [[ -z $days ]];then
	log_info "time_label should be non-empty"
	help
fi

log_info "will clean dir: $input_dir before days: $days"
# find "${input_dir}/" -maxdepth 1 -type d  -mtime +${hour}  -print -exec rm -vrf {} \;
log_info "exec cmd: find ${input_dir}/ -maxdepth 1 -type d  -mtime +${days}  -print"
find "${input_dir}/" -maxdepth 1 -type d  -mtime +${days} -print -exec rm -vrf {} \;
log_info "disk clean done"
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75



Last Updated: 11/27/2023, 3:58:44 PM
Apache License 2.0 | Copyright © 2022 by xueliang.wu 苏ICP备15016087号