Created
March 20, 2020 16:40
-
-
Save michaeldye/b3ea0a5f60305575657143c75ce19275 to your computer and use it in GitHub Desktop.
Prune oldest of files matching a "find" name pattern leaving NUM_KEEP on disk (useful for deleting old backups)
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 | |
# | |
# Note: Ignores files with ".part" suffix | |
# | |
NUM_KEEP=5 | |
# example invocation: /usr/local/bin/prune-old /backup "gitlab-embedded-db*.dump" | |
# | |
function usage() { | |
echo "Usage: $0 'dir' 'pattern'" >&2 | |
} | |
(($# < 2)) && { | |
echo "Error in invocation" >&2 | |
usage | |
exit 1 | |
} | |
dir="$1"; shift | |
pattern="$1"; shift | |
declare -a files | |
files=( $(find "$dir" -name "$pattern" -type f -and -not -name "*.part" -printf "%T@ %Tc %p\n" | sort -n | awk '{print $NF}') ) | |
echo "Total files to consider for pruning given pattern \"$pattern\" (${#files[@]}): ${files[@]}" >&2 | |
ex=0 | |
((${#files[@]} > NUM_KEEP)) && { | |
ct=0 | |
for file in "${files[@]}"; do | |
((ct == ${#files[@]}-NUM_KEEP)) && { | |
echo "Deleted enough old files ($ct), leaving the rest ($NUM_KEEP)" >&2 | |
break | |
} | |
echo "++ Deleting $file" | |
rm -f "$file" || { | |
ex=4 | |
break | |
} | |
ct=$((ct+1)) | |
done | |
} | |
((ex > 0)) && { | |
echo -e "\nError occured" >&2 | |
} | |
echo "Exiting." | |
exit $ex |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment