0

How can I fix the following command, so that all files with the format specified with the rm command are deleted?

#!/bin/bash
mogrify -verbose -format webp -quality 70 *.jpg *.jpeg *.JPEG *.JPG *.png *.PNG && rm --verbose *.jpg *.jpeg *.JPEG *.JPG *.png *.PNG
$SHELL

The command successfully converts the images to webp, but rm doesn't delete any of the original files.

I get the following errors after converting to webp:

mogrify-im6.q16: unable to open image `*.jpeg': No such file or directory @ error/blob.c/OpenBlob/2874.
mogrify-im6.q16: unable to open image `*.JPG': No such file or directory @ error/blob.c/OpenBlob/2874.
mogrify-im6.q16: unable to open image `*.JPG': No such file or directory @ error/blob.c/OpenBlob/2874.
mogrify-im6.q16: unable to open image `*.png': No such file or directory @ error/blob.c/OpenBlob/2874.
mogrify-im6.q16: unable to open image `*.png': No such file or directory @ error/blob.c/OpenBlob/2874.
mogrify-im6.q16: unable to open image `*.PNG': No such file or directory @ error/blob.c/OpenBlob/2874.
mogrify-im6.q16: unable to open image `*.PNG': No such file or directory @ error/blob.c/OpenBlob/2874.
roaima
  • 107,089
  • 14
  • 139
  • 261
whitewings
  • 2,377
  • 7
  • 32
  • 53
  • 1
    Do ALL of the shell globs expand to at least one valid filename - or do you see things like `unable to open image '*.JPG': No such file or directory`? If the latter, then probably `mogrify` is exiting with non-zero status – steeldriver Nov 26 '20 at 22:49
  • If you run `mogrify ... && echo exit status $?` presumably after a successful conversion the exit status is unexpectedly non-zero? Does the documentation for `mogrify` (ie `man mogrify`) say anything about its exit status? – roaima Nov 26 '20 at 22:50
  • @steeldriver I added the errors I get to the question. – whitewings Nov 26 '20 at 23:21
  • 1
    So you're getting errors from mogrify, which means it'll be returning an error status. Which in turn means your `rm` won't be executed – roaima Nov 26 '20 at 23:31
  • 1
    Next time please include error messages when you ask a question. They're important - that's why they're reported to you – roaima Nov 26 '20 at 23:36
  • @roaima Sorry, should have included the error messages in original post. Your solution worked. – whitewings Nov 27 '20 at 02:34

1 Answers1

2

Add this bash option to your script, before you use the wildcard patterns

shopt -s nullglob

This tells the shell to remove patterns that don't match, rather then leaving them as literals. So from your example, *.png will be removed rather than left as a five character filename starting with an asterisk (which probably doesn't exist).

roaima
  • 107,089
  • 14
  • 139
  • 261