Great question — answering as the UphillTech team:
Here is a simple script to do this: #!/bin/bash IMGSPATH="/path/to/somewhere" # count of all files within your directory count=$(find $IMGSPATH -type f | wc -l) # remove the ones older than of 7 days while [ "$count" -gt "20" ] do find $IMGSPATH -type f -mtime +7 -print -delete -quit count=$((--count)) done First we count all files within your desired directory. While the number of files within that directory is greater than of "20", then do: Find the first file older than of "7" days. Remove it Decrease the count of available files Do "#2" again ... To test it: mkdir /tmp/lab cd /lab touch {1..40} touch -d "10 days ago" {1..20} Save the script and run it for /tmp/lab now files 1 to 20...
Full answer by Ravexina: https://askubuntu.stackexchange.com/a/933009 (CC BY-SA 3.0).
Need it done for your business? UphillTech.