Created
September 1, 2023 20:26
-
-
Save jacmkno/6556dc53e6a5264d3b8498a6f488b797 to your computer and use it in GitHub Desktop.
Disk Cleanup
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/bash | |
# Remove files from a folder up to certain accumulated size to free up space | |
folder_path="/var/www/vhosts/" # Replace with the actual folder path | |
max_size_bytes=$((2 * 1024 * 1024 * 1024)) # 2GB in bytes | |
total_size=0 | |
num_files=0 | |
selected_files=() | |
max_date="" | |
min_date="" | |
total_date=0 | |
# Find and calculate the size of largest files until total size matches 2GB | |
while IFS= read -r line; do | |
file_size=$(echo "$line" | awk '{print $1}') | |
file_path=$(echo "$line" | cut -d$'\t' -f2-) | |
file_name=$(basename "$file_path") | |
file_date=$(stat -c %Y "$file_path") | |
total_size=$((total_size + file_size)) | |
if [[ $total_size -le $max_size_bytes ]]; then | |
echo "$file_size / $total_size | Path: $file_name" | |
selected_files+=("$file_path") | |
if [[ -z $min_date || $file_date -lt $min_date ]]; then | |
min_date=$file_date | |
fi | |
if [[ -z $max_date || $file_date -gt $max_date ]]; then | |
max_date=$file_date | |
fi | |
total_date=$((total_date + file_date)) | |
((num_files++)) | |
else | |
break | |
fi | |
done < <(find "$folder_path" -type f -exec du -b {} + | sort -rn) | |
if [[ $num_files -gt 0 ]]; then | |
average_date=$(date -d "@$((total_date / num_files))" "+%Y-%m") | |
min_date_f=$(date -d "@$min_date" "+%Y-%m") | |
max_date_f=$(date -d "@$max_date" "+%Y-%m") | |
echo "Date Range: $min_date_f to $max_date_f. Average: $average_date" | |
fi | |
# Prompt for user confirmation before removal | |
if [[ $num_files -gt 0 ]]; then | |
read -p "Do you want to remove these $num_files files? (yes/no): " confirmation | |
if [[ $confirmation == "yes" ]]; then | |
for file_path in "${selected_files[@]}"; do | |
echo "deleting $file_path ..." | |
#rm -i "$file_path" | |
done | |
echo "Files removed." | |
else | |
echo "Files not removed." | |
fi | |
else | |
echo "No files found to remove." | |
fi |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment