-
Notifications
You must be signed in to change notification settings - Fork 2
/
delete_old_backup_files.sh
127 lines (111 loc) · 2.64 KB
/
delete_old_backup_files.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
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
#!/bin/bash
#######################
# cleaner.sh
# by imperialWicket
#
# version 1.0.1
#######################
# cleaner usage function
usage()
{
cat << EOF
cleaner.sh
This script cleans directories. It is useful for backup
and log file directories, when you want to delete older files.
USAGE: cleaner.sh [options]
OPTIONS:
-h Show this message
-q This script defaults to verbose, use -q to turn off messages
(Useful when using the cleaner.sh in automated scripts).
-s A search string to limit file deletion, defaults to '*' (All files).
-m The minimum number of files required in the directory (Files
to be maintained), defaults to 5.
-d The directory to clean, defaults to the current directory.
EXAMPLES:
In the current directory, delete everything but the 5 most recently touched
files:
cleaner.sh
Same as:
cleaner.sh -s * -m 5 -d .
In the /home/myUser directory, delete all files including text "test", except
the most recent:
cleaner.sh -s test -m 1 -d /home/myUser
Don't ask for any confirmation:
cleaner.sh -s test -m 1 -d /home/myUser -q
EOF
}
# Set default values for VARS
SEARCH_STRING='*'
MIN_FILES='5'
DIR='.'
QUIET=0
DELETED=0
# cleaner delete files function
delete()
{
FILES=`ls -1p "$SEARCH_STRING"* 2>/dev/null | grep -vc "/$"`
while [ $FILES -gt $MIN_FILES ]
do
ls -tr "$SEARCH_STRING"* 2>/dev/null | head -1 | xargs -i rm {}
FILES=`ls -1p "$SEARCH_STRING"* 2>/dev/null | grep -vc "/$"`
let "DELETED+=1"
done
}
# cleaner set args and handle help/unknown arguments with usage() function
while getopts ":s:m:d:qh" flag
do
#echo "$flag" $OPTIND $OPTARG
case "$flag" in
h)
usage
exit 0
;;
q)
QUIET=1
;;
s)
SEARCH_STRING=$OPTARG
;;
m)
MIN_FILES=$OPTARG
;;
d)
DIR=$OPTARG
;;
?)
usage
exit 1
esac
done
# cleaner change to requested directory and perform delete with or without verbosity
cd $DIR
CONFIRM_FILES=`ls -1p "$SEARCH_STRING"*`
if [ $QUIET = 0 ]
then
if [ $MIN_FILES = 0 ]
then
echo 'Delete the following files (y/n)?'
else
echo Delete the following files except the $MIN_FILES 'most recently touched (y/n)?'
fi
echo $CONFIRM_FILES
read CONFIRM
if [ $CONFIRM = y ] || [ $CONFIRM = Y ] || [ $CONFIRM = YES ] || [ $CONFIRM = yes ] || [ $CONFIRM = Yes ]
then
delete
if [ $DELETED = 1 ]
then
TEXT='file.'
else
TEXT='files.'
fi
echo Removed $DELETED $TEXT
else
echo Cleaner canceled.
fi
else
delete
fi
# cleaner change back to the original directory
cd $OLDPWD
exit 0