Created
July 4, 2017 09:37
-
-
Save wakumaku/8eb1aa13d374eb7b67b1c2b27a1e7f42 to your computer and use it in GitHub Desktop.
Script to delete old files in a directory by a pattern
This file contains hidden or 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 | |
# set -x | |
BASE_DIR=/backups | |
TOTAL_KEEP=10 | |
FIND_EXPRESSION="[0-9].+\_backup\.tar\.gz" | |
TOTAL_BACKUPS=`ls $BASE_DIR| egrep "$FIND_EXPRESSION" | wc -l` | |
RESULT=`expr $TOTAL_BACKUPS - $TOTAL_KEEP` | |
if [ "$RESULT" -le "0" ];then | |
echo "No files found to delete" | |
exit 0 | |
fi | |
FILES_TO_REMOVE=`ls $BASE_DIR| egrep "$FIND_EXPRESSION" | head -n $RESULT -` | |
echo "Files to remove $RESULT:" | |
echo $FILES_TO_REMOVE | |
for FILEX in ${FILES_TO_REMOVE} | |
do | |
echo "> Deleting ..." | |
echo $BASE_DIR/$FILEX | |
rm $BASE_DIR/$FILEX | |
echo "> Done!" | |
echo "-" | |
done | |
echo "Maintenance finished!" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment