Skip to content

Instantly share code, notes, and snippets.

@wakumaku
Created July 4, 2017 09:37
Show Gist options
  • Save wakumaku/8eb1aa13d374eb7b67b1c2b27a1e7f42 to your computer and use it in GitHub Desktop.
Save wakumaku/8eb1aa13d374eb7b67b1c2b27a1e7f42 to your computer and use it in GitHub Desktop.
Script to delete old files in a directory by a pattern
#!/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