Martin Martin - 7 months ago 9
Bash Question

Shell: Delete filename.foo if filename.bar doesn't exist

I want to check all JPGs in a directory (rf). If no WEBP file with the same filename exists > delete the JPG file.

Example:


  • /a/1.jpg (ok)

  • /a/1.webp

  • /x/2.jpg (del)

  • /x/3.jpg (ok)

  • /x/3.webp


Answer

I won't give you the full script so you have a chance to figure it out and learn something. Here's how to chop off and append strings:

jpg="/a/1.jpg"
webp="${jpg%.jpg}.webp"
if ! test -f "$webp"; then rm -f -- "$jpg"; fi