How to delete the oldest file if there are more than X files in the current working directory - Linux Bash
Doing some routine tasks I just needed a script to delete the oldest file if there are more than X files in the current directory.
A backup was set up for being done every day at 3:00 am, but I just wanted to keep the last 2 recent files and delete always the third file as the oldest one, so the solution was given to it with this:
NUMBER=$(find *.gz -type f -printf '%T+ %p\n' | sort | awk -F ' ' '{print $2}' | wc -l)
echo "number of files:" "$NUMBER"
#find out which file is the oldest
#OLDEST=$(ls -rt | head -n 1)
OLDEST=$(find *.gz -type f -printf '%T+ %p\n' | sort | awk -F ' ' '{print $2}' | head -n 1)
echo "oldest file:" "$OLDEST"
#delete oldest file if there are 2 files or more
if [ "$NUMBER" -gt 2 ] ; then
rm "$OLDEST"
else echo "there are 2 or less files, no file is deleted"
fi
A backup was set up for being done every day at 3:00 am, but I just wanted to keep the last 2 recent files and delete always the third file as the oldest one, so the solution was given to it with this:
NUMBER=$(find *.gz -type f -printf '%T+ %p\n' | sort | awk -F ' ' '{print $2}' | wc -l)
echo "number of files:" "$NUMBER"
#find out which file is the oldest
#OLDEST=$(ls -rt | head -n 1)
OLDEST=$(find *.gz -type f -printf '%T+ %p\n' | sort | awk -F ' ' '{print $2}' | head -n 1)
echo "oldest file:" "$OLDEST"
#delete oldest file if there are 2 files or more
if [ "$NUMBER" -gt 2 ] ; then
rm "$OLDEST"
else echo "there are 2 or less files, no file is deleted"
fi
just replace the number 2 in [ "$NUMBER" -gt 2 ] by the number of files you want to have
Comments
Post a Comment