-
Notifications
You must be signed in to change notification settings - Fork 0
/
cleanup-directories.sh
executable file
·106 lines (99 loc) · 2.1 KB
/
cleanup-directories.sh
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
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
#!/bin/bash
#
# Directory Cleanup Script - Remove any old files in a specified directory
#
# Free to use commercially or non-commercially provided acknowledgement
# of the author is retained.
#
# History
# -------
# 2008-12-22 Sid Young Created script to clean up old files to reduce disk space
TARGET_DIR=/tmp
KEEP_DAYS=90
HOST=`hostname`
#
# Common Logging Code
#
function LogStart
{
echo "====== Log Start =========" >> $LF
echo "Time: `date`" >> $LF
echo " " >> $LF
}
function LogEnd
{
echo " " >> $LF
echo "Time: `date`" >> $LF
echo "====== Log End =========" >> $LF
}
function LogMsg
{
echo "`date '+%Y-%m-%d|%H:%M:%S|'`$$|OK|$1" >> $LF
}
function LogError
{
echo "`date '+%Y-%m-%d|%H:%M:%S|'`$$|ERROR|$1" >> $LF
}
function LogCritical
{
echo "`date '+%Y-%m-%d|%H:%M:%S|'`$$|CRITICAL|$1" >> $LF
}
UMASK=002
FILE_DATE=`date '+%Y-%m-%d'`
LF_DIR=/logs/cron
LF=$LF_DIR/dircleanup-$FILE_DATE.log
mkdir -p $LF_DIR
chmod 777 /logs/cron
touch $LF
chmod 644 $LF
#----------------------------------------
#
# Process any command line parameters
#
#----------------------------------------
LogStart
set -- getopt dr: "$@"
while [ $# -gt 0 ]
do
case "$1" in
-d) TARGET_DIR="$2" ;;
-r) KEEP_DAYS="$2" ;;
esac
shift
done
LogMsg "Target directory: $TARGET_DIR"
LogMsg "Retension Period: $KEEP_DAYS"
if [ -d "$TARGET_DIR" ]
then
cd $TARGET_DIR
LogMsg "$TARGET_DIR exists - Locating files to delete"
CNT=`find $TARGET_DIR -type f -mtime +$KEEP_DAYS -print | wc -l`
#
# Find the files and list them to the log
#
find $TARGET_DIR -type f -mtime +${KEEP_DAYS} -print > /tmp/cleanup-list-$$
LogMsg "File list is:"
LogMsg "-------------"
for file in `cat /tmp/cleanup-list-$$`
do
LogMsg $file
done
LogMsg " "
for file in `cat /tmp/cleanup-list-$$`
do
rm $file > /dev/null 2>&1
if [ $? -eq 1 ]
then
LogMsg "File $file Not Found?"
fi
done
LogMsg "Done $CNT files removed"
else
LogCritical "Aborting - $TARGET_DIR does not exist"
echo "ERROR on Host ${HOST} - Target for cleanup [ $TARGET_DIR ] does not exist - aborting" | mailx -s "[CRON] Cleanup failed" $EMAIL
fi
rm -f /tmp/cleanup-list-$$
LogEnd
#
# End of file
#