Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

Wondering how would one go about writing a script that:

Counts the number of files in a directory.

If that number is greater than a specified number N, delete the oldest file in the directory.

For bonus feelings of good will: Only included .zip files in the count/delete.

share|improve this question
This feels a little like we may be doing school or real work for @Ryan. Perhaps you can demonstrate what you have come up with so far. – uther May 14 '12 at 20:53
It's not that I don't want to help, otherwise I wouldn't spend time here. What you are asking for is fairly trivial. It would go a long way to see you make an effort to write a script first and ask for critique/improvements instead of asking someone to write the script for you from scratch. I want you to learn something. – uther May 14 '12 at 20:58
man find, man wc, man ls – Nils May 14 '12 at 21:00
Why all the down-votes? BTW, possibly relevant reading. – jw013 May 14 '12 at 21:28
When you mouse over the downvote button it says: "This question does not show any research effort". If that doesn't apply here, when does it apply? – Mikel May 14 '12 at 22:52
[[ $( ls | wc -l ) -gt $N ]] && ls -tr | tail -n1 | xargs echo rm

Barely tested, but I think this comes close. If you are happy with the text output, you can remove the echo to set it live.

  • ls list files
  • wc count them
  • [[ ... -gt ... ]] if
  • && then
  • ls -tr list files in reverse age
  • tail -n1 show only last line
  • xargs echo rm append every argument found to echo rm
  • echo rm give you the opportunity to check if the result is really what you want
  • rm remove file
share|improve this answer
This will break on filenames containing newlines. – Chris Down May 14 '12 at 21:46
This will break on filenames containing any kind of whitespace or \'". – Gilles May 14 '12 at 23:11
Schoolbook assignments don't have newlines and quotes in filenames. ;o) – jippie May 15 '12 at 6:28
@jippie this is for my minecraft server backups :) – ioSamurai May 15 '12 at 15:44
Same for minecraft server backups ;o) (just guessing) – jippie May 15 '12 at 19:07

For example, to only perform the actions if there are more than 50 files in the folder:

shopt -s dotglob nullglob
for file in *; do
    [[ -f $file ]] && files+=( "$file" )
if (( ${#files[@]} > 50 )); then
    IFS= read -r -d $'\0' line < <(find . -maxdepth 1 -type f -printf '%T@ %p\0' 2>/dev/null | sort -z -n)
    rm "${line#* }"
share|improve this answer

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.