0

I have a game server. It auto-gets players’ screenshots and stores at /home/gameserver/serverfiles/screenshots.

I want to delete old screenshots when it reaches 1000. I mean if it’s 1000 screenshots, when a new screenshot comes, it auto-deletes the 1000th screenshot.

How can I do that, which scripts can I use? Can anyone give suggestion or codes?

Note: I am using Ubuntu 18.04 and my game server user hasn't sudo access.

I want to maintain my screenshot folder to hold max 1000 images.

αғsнιη
  • 35,660
GHOST
  • 347

1 Answers1

3

Assuming format to be any of the jpg, jpeg and png you can write a short script which counts and deletes all files if the count is >=1000. A short working example would be:

#!/bin/bash

count=`ls -l *.{jpg,jpeg,png} | wc -l`

if [ $count -gt 1000 ]
then 
    echo "Deleting old 1000 image files"
    for i in $(ls -lt *.{jpg,jpeg,png} | head -n 1000)
    do
        rm $i
    done
fi

You can then add this script to crontab to execute it every 10 minutes(for example). Type crontab -e to edit it.

  • Yes you're right I will edit the script for automated deletion of only the first 1000 files when sorted datewise – Prathu Baronia Aug 27 '18 at 10:58
  • @Melebius I have made the edits – Prathu Baronia Aug 27 '18 at 11:04
  • Made the change – Prathu Baronia Aug 27 '18 at 11:34
  • Just a couple of thoughts. If you replace head -n 1000 with tail -n -1000 it will output the oldest files where there are more than 1000 files (so if you have 1007 files, it will report the 7 oldest files which you can then delete. Also watch out for file names with a space in them (may not be relevant on your system), but you may want to quote (") $i in the rm line and the $( ...) section – Nick Sillito Aug 27 '18 at 12:12