If I have a process that creates output jpg files. I have a cleanup script where I want to clean all files except the 100 last files. I used this command:
find -H /tmp -name \*.jpg | xargs ls -rt | head -n -100 | xargs rm -f
This works fine, except when not a single jpg file is present, in that case the find command will produc no output; so ls -rt
will start listing ALL files in /tmp and start removing random files that don't match the *.jpg
patter. I use a workaround like this:
JPG_FILES=$(find -H /tmp -name \*.jpg)
if [ -n "$JPG_FILES" ]
then
echo $JPG_FILES | xargs ls -rt | head -n -100 | xargs rm -f
fi
which works fine, but I think there might be a better workaround, or just a better way to do this kind of cleanup?
PS: I know about this question, but that gives me the bug where random old files are removed that are not jpgs.