-4

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.

MetaGuru
  • 719

2 Answers2

1
N=50
[[ $( ls | wc -l ) -gt $N ]] && ls -tr | tail -n1 | tr \\n \\0 | xargs -0 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 (replace 1 as needed)
  • tr \\n \\0 make \0 the delimiter between filenames (only one here)
  • xargs -0 echo rm -- append every argument (delimited by \0s) found to echo rm --
  • echo rm -- give you the opportunity to check if the result is really what you want
  • rm -- remove file (put -- before filenames to handle filenames starting with -)
Ned64
  • 8,726
jippie
  • 14,086
1

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" )
done
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#* }"
fi
Chris Down
  • 125,559
  • 25
  • 270
  • 266