Skip to content

Instantly share code, notes, and snippets.

@patryk
Created March 31, 2015 12:41
Show Gist options
  • Save patryk/00f99468cc381412ec0f to your computer and use it in GitHub Desktop.
Save patryk/00f99468cc381412ec0f to your computer and use it in GitHub Desktop.
Keep n newest directories deleting all older in a specified directory
#!/usr/bin/env bash
dir="$1"
min_dirs=5
exclude=$(readlink -f $(find "$dir" -maxdepth 1 -type l))
while [ $(find "$dir" -maxdepth 1 -type d -not -path $exclude | wc -l) -gt $min_dirs ] && IFS= read -r -d $'\0' line < <(find "$dir" -maxdepth 1 -type d -not -path $exclude -printf '%T@ %p\0' 2>/dev/null | sort -z -n);
do
file="${line#* }"
ls -1Ld "$file" | xargs rm -r
done
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment