#!/bin/bash # # prune_dir - prune directory by deleting files if we are low on space # DIR_FROM=$1 DIR_TO=$2 CAPACITY_LIMIT=$3 if [ "$DIR_FROM" == "" ] then echo "ERROR: directory not specified" exit 1 fi if ! cd $DIR_FROM then echo "ERROR: unable to chdir to directory '$DIR_FROM'" exit 2 fi if [ "$DIR_TO" == "" ] then echo "ERROR: directory not specified" exit 1 fi if ! cd $DIR_TO then echo "$DIR_TO not found. Mkdir for new directory!'" mkdir $DIR_TO if [ ! cd $DIR_TO ] then echo "ERROR: Didn't create specific directory! Something went wrong! Exit from script!" exit 1 fi fi if ! [[ "$CAPACITY_LIMIT" =~ ^[0-9]+$ ]] then echo "Sorry integers only" exit 1 fi if [ "$CAPACITY_LIMIT" == "" ] || [ "$CAPACITY_LIMIT" -lt 60 ] then CAPACITY_LIMIT=90 # default limit fi CAPACITY=$(df -k $DIR_FROM | awk '{gsub("%",""); capacity=$5}; END {print capacity}') while [ $CAPACITY -gt $CAPACITY_LIMIT ] do oldest_file=$(find $DIR_FROM -type f -printf '%T+ %p\n' | sort | head -n 1 | tr -s ' ' | cut -d ' ' -f2) file_size=$(du -k $oldest_file | cut -f1) free_space=$(df -k $DIR_TO | awk '{gsub("%",""); capacity=$4}; END {print capacity}') zero_size=0 if [ $file_size -gt $free_space] then SECOND_CAPACITY=$(df -k $DIR_TO | awk '{gsub("%",""); capacity=$5}; END {print capacity}') test_limit=6 while [ $SECOND_CAPACITY -gt $test_limit ] do second_disk_old_file=$(find $DIR_TO -type f -printf '%T+ %p\n' | sort | head -n 1 | tr -s ' ' | cut -d ' ' -f2) parent_second_directory_path=$(dirname $second_disk_old_file) files_number_second=$(find $parent_second_directory_path -type f | wc -l) rm -rf $second_disk_old_file if [ $files_number_second -eq 1 ] then rm -rf $parent_second_directory_path fi SECOND_CAPACITY=$(df -k $DIR_TO | awk '{gsub("%",""); capacity=$5}; END {print capacity}') done fi parent_directory_name=$(dirname $oldest_file | sed 's,^\(.*/\)\?\([^/]*\),\2,') parent_directory_path=$(dirname $oldest_file) grand_parent_directory_path=$(dirname $parent_directory_path) grand_parent_directory_name=$(dirname $parent_directory_path | sed 's,^\(.*/\)\?\([^/]*\),\2,') dest_grand_parent_directory_path="${DIR_TO}/$grand_parent_directory_name" dest_directory_path="${dest_grand_parent_directory_path}/$parent_directory_name" if [ ! -d $dest_grand_parent_directory_path ] then mkdir $dest_grand_parent_directory_path if [ ! -d $dest_grand_parent_directory_path ] then echo "ERROR" exit 1 else mkdir $dest_directory_path if [ ! -d $dest_directory_path ] then echo "ERROR" exit 1 fi fi else mkdir $dest_directory_path if [ ! -d $dest_directory_path ] then echo "ERROR" exit 1 fi fi parent_directory_path=$(dirname $oldest_file) echo "---------------" echo "PRZENOSZE: $oldest_file" echo "DO: $dest_directory_path" echo $'---------------\n' mv $oldest_file $dest_directory_path files_number=$(find $parent_directory_path -type f | wc -l) a=0 if [ $files_number -eq $a ] then rm -rf $parent_directory_path fi CAPACITY=$(df -k $DIR_FROM | awk '{gsub("%",""); capacity=$5}; END {print capacity}') done