Created
February 14, 2018 23:34
-
-
Save RonanKER/01c4872775632ea51b43af04ed7d01e6 to your computer and use it in GitHub Desktop.
a test about cleaning oldest files matching pattern in a directory
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
#Exemple of configurable cleaner for oldest file in a directory | |
# Use case of this exemple : | |
# * a script that uses a temp file (writing timestamp in its name for exemple) | |
# * by default it removes its temp file at the end (and only this one) | |
# * for debug purpose we would like to keep the file, or several historic files | |
# * with "KEEP_FILE" we can set : 0 (clean all) 1 (only latest) X (youngest files) "ALL" (keep all files) | |
#configuration | |
TARGET_DIR=~/tmp/test | |
KEEP_FILE=3 | |
FILE_PREFIX=file_ | |
FILE_SUFFIX=.ext | |
#simulate state for testing | |
i=0 | |
while [ $i -ne 5 ] ; do | |
touch $TARGET_DIR/$FILE_PREFIX$i$FILE_SUFFIX | |
i=$(($i + 1)) | |
done | |
CURRENT_FILE="$FILE_PREFIX$(date +%Y%m%d_%H%M%S)$FILE_SUFFIX" | |
touch $TARGET_DIR/$CURRENT_FILE | |
# And now the code | |
#clean oldest files matching prefix and suffix, keeping $KEEP_FILE files | |
# - by default ('undefined' or unsupported value) : just removes CURRENT_FILE | |
# - Number = 0 : removes all dumps | |
# - Number > 0 : keep this number of files (so if 1 then keep only CURRENT_FILE) | |
# - "ALL" : keep all files | |
if [ "x$KEEP_FILE" == "xALL" ] | |
then | |
echo "keep all files" | |
elif [ $KEEP_FILE -ge 0 ] 2>/dev/null | |
then | |
if [ $KEEP_FILE -ne 0 ] ; then | |
echo "current file : $TARGET_DIR/$CURRENT_FILE" | |
else | |
echo "removing all files" | |
fi | |
NUMBER=$((KEEP_FILE+1)) | |
echo "cleaning oldest files (keeping $KEEP_FILE files)" | |
cd $TARGET_DIR/ | |
for each in $( ls -t1 $FILE_PREFIX*$FILE_SUFFIX | tail -n+$NUMBER) ; do echo "remove $each"; rm $each; done | |
#Note : I prefer 'foreach' beacause it enables several complex actions in 'do' block, | |
#whereas 'xargs' would need a sub-script, and also prints an error when there is nothing to do : | |
#ls -t1 $FILE_PREFIX*$FILE_SUFFIX | tail -n+$NUMBER | xargs rm -v | |
cd - >/dev/null | |
else | |
echo "remove current file" | |
rm $TARGET_DIR/$CURRENT_FILE | |
fi |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment