-
Notifications
You must be signed in to change notification settings - Fork 1
/
cleanup.sh
executable file
·65 lines (52 loc) · 1.19 KB
/
cleanup.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
#!/bin/bash
# Cleanup script
# Removes the last n files from a directory listing
#
# Usage:
#
# cleanup.sh <DIRECTORY> <BASENAME> <LIMIT>
#
# Copyright: ZeyOS, Inc. 2016
# Author: Peter-Christoph Haider <peter.haider@zeyos.com>
# License: MIT
DIR=${1%/}
BASENAME="$2"
LIMIT="$3"
USAGE=$'\n\nUsage:\n cleanup.sh <DIRECTORY> <BASENAME> <LIMIT>\n'
if [[ -z "$LIMIT" ]]; then
echo "No limit defined!${USAGE}"
exit 1
fi
if ! [[ $LIMIT =~ ^-?[0-9]+$ ]]; then
echo "Limit is not a number!"
exit 1
fi
if [[ -z "$BASENAME" ]]; then
echo "No basename defined!${USAGE}"
exit 1
fi
if [[ -z "$DIR" ]]; then
echo "No directory defined!${USAGE}"
exit 1
fi
if [ ! -d $DIR ]; then
echo "Target directory does not exist: ${DIR}"
exit 1
fi
FILECOUNT=$(ls ${DIR} | grep "${BASENAME}" | wc -l)
if [ $FILECOUNT -lt $LIMIT ] ; then
# Nothing to do
exit 0
fi
# Loop over all files and remove the oldest ones
# Files are being sorted by name, so make sure your filename reflects
# the corresponding date
COUNTER=0
FILELIST=$(ls ${DIR} | grep "${BASENAME}" | sort -r)
for FILENAME in $FILELIST; do
COUNTER=$((COUNTER+1))
if [ $COUNTER -gt $LIMIT ] ; then
rm -f $FILENAME
fi
done
exit 0