Retain X amount of files

I encountered an issue today where someone requested that we keep the 10 newest backup files, while the rest of them (the oldest) were deleted. So I made this little script:


NUMBER_OF_FILES="$(ls -t $FILE_DIR | wc -l)"

if [ "$NUMBER_OF_FILES" -ge "$RETAIN" ]; then
    cd $FILE_DIR
    ls -t | sed -e "1,$RETAIN d" | xargs rm -f

This can be modified to match with any type of file or filename.