Created
December 3, 2020 00:29
-
-
Save adrianlungu/5612787b13bbb14cd003e091300c4749 to your computer and use it in GitHub Desktop.
Delete oldest directory in another directory when hdd is out of space
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 | |
# | |
# prune_dir - prune directory by deleting files if we are low on space | |
# | |
DIR=$1 | |
CAPACITY_LIMIT=$2 | |
if [ "$DIR" == "" ] | |
then | |
echo "ERROR: directory not specified" | |
exit 1 | |
fi | |
if ! cd $DIR | |
then | |
echo "ERROR: unable to chdir to directory '$DIR'" | |
exit 2 | |
fi | |
if [ "$CAPACITY_LIMIT" == "" ] | |
then | |
CAPACITY_LIMIT=95 # default limit | |
fi | |
CAPACITY=$(df -k . | awk '{gsub("%",""); capacity=$5}; END {print capacity}') | |
if [ $CAPACITY -gt $CAPACITY_LIMIT ] | |
then | |
while true; do | |
# Find and delete the oldest file | |
# in subdirectories of the directory | |
find . -mindepth 2 -type d -printf '%T+ %p\n' | sort | awk 'NR==1{print $2}' | xargs r$ | |
# Check capacity | |
CAPACITY=$(df -k . | awk '{gsub("%",""); capacity=$5}; END {print capacity}') | |
if [ $CAPACITY -le $CAPACITY_LIMIT ] | |
then | |
# we're below the limit, so stop deleting | |
exit | |
fi | |
done | |
fi |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment