-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdeleteFoldersCountMoreThen200.sh
40 lines (29 loc) · 1.59 KB
/
deleteFoldersCountMoreThen200.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
#!/bin/bash
# This script deletes the oldest folders matching a specified pattern in a given directory while ensuring
# at least 200 folders remain. It sorts all matching directories by modification time, oldest first,
# calculates how many to delete if there are more than 200, and then removes the excess oldest folders.
# This can be useful for maintaining space or managing backups.
# Additionally, this script uses a lock file to prevent concurrent execution.
# Folder pattern to match
folder_pattern="oplog.rs_data_till"
# Directory where to look for folders (using current directory by default)
target_dir="/mongo-oplog-dump/data/"
# Minimum number of folders to keep
min_folders_to_keep=200
# Get all directories matching the pattern, sorted by modification time (oldest first)
folders=($(find "$target_dir" -maxdepth 1 -type d -name "$folder_pattern*" ! -path "$target_dir" -printf '%T@ %p\n' | sort -n | awk '{print $2}'))
# Count the number of folders
folder_count=${#folders[@]}
# If we have more than the minimum number of folders, delete the excess
if [ "$folder_count" -gt "$min_folders_to_keep" ]; then
# Calculate how many folders to delete
folders_to_delete=$((folder_count - min_folders_to_keep))
echo "Deleting oldest $folders_to_delete folders matching $folder_pattern:"
# Loop through the array from the beginning to delete oldest folders
for (( i=0; i<folders_to_delete; i++ )); do
echo "Removing ${folders[i]}"
rm -rf "${folders[i]}"
done
else
echo "Not enough folders matching $folder_pattern to delete. Current count: $folder_count"
fi