Skip to content

Instantly share code, notes, and snippets.

@coopernurse
Created October 14, 2015 23:16
Show Gist options
  • Save coopernurse/1b403599ced7f4cf4db7 to your computer and use it in GitHub Desktop.
Save coopernurse/1b403599ced7f4cf4db7 to your computer and use it in GitHub Desktop.
bash script to free up disk space up to a threshold
#!/bin/bash
dir="$1"
if [ ! -d "$dir" ]; then
echo "$dir is not a directory. Exiting."
exit 1
fi
minimum="$2"
if [ -z "$minimum" ]; then
minimum="5120000"
fi
function get_free {
free=$(df -P "$dir" | tail -1 | awk '{print $4}')
}
get_free
while [ "$free" -lt "$minimum" ]
do
oldest=$(find $dir -maxdepth 1 -mindepth 1 -type d -printf "%C@ %p\n" | grep -v 'lost+found' | sort | head -1 | awk '{print $2}')
if [ -z "$oldest" ]; then
echo "No directories remain in $dir - cannot reclaim enough space."
exit 2
fi
echo "Removing: $oldest"
/bin/rm -rf "$oldest"
get_free
done
echo "$dir has more than $minimum blocks available"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment