This question pertains to the situation where
- An image was uploaded, say
mypicture.jpg
- WordPress created multiple copies of it with different resolutions like
mypicture-300x500.jpg
andmypicture-600x1000.jpg
- You delete the original image only
In this scenario, the remaining photos on the filesystem are mypicture-300x500.jpg
and mypicture-600x1000.jpg
.
How can you script this to find these "dangling" images with the missing original and delete the "dangling" images.
2
Answers
I've written a Bash script that will attempt to find the original filename (i.e.
mypicture.jpg
) based on scraping away the WordPress resolution (i.e.mypicture-300x500.jpg
), and if it's not found, delete the "dangling image" (i.e.rm -f mypicture-300x500.jpg
)You could use
find
to find all lower resolution pictures with the-regex
test:And this would be much better than trying to parse the
ls
output which is for humans only, not for automation. A safer (and simpler) bash script could thus be:(delete the
echo
once you will be convinced that it works as expected).Bash loops are OK but they tend to become really slow when the number of iteration increases. So, let’s incorporate our simple bash script in a single
find
command with the-exec
action:This will print a list of files. Check that it is correct and, once you will be satisfied, add the
-delete
action:See
man find
andman bash
for more explanations.Demo: