I was using this little script to find malformed images:
find -name '*.jpg' -exec identify -format "%f\n" {} \; 2>errors.txt
It worked well enough, but now I need to modify it slightly. Instead of dumping the stderr to errors.txt, I want to dump the filename (%f) of the image that triggered the error. That is, I want a list of the malformed image files in errors.txt instead of a list error messages.
I tried adding || echo "%f" >> errors.txt to the -exec portion, but that didn't work. What would be the best way to do this?
Best Answer
This finds malformed images and stores their names in
names.txt
:How it works
find -name '*.jpg'
This starts up
find
as usual.-exec bash -c 'identify "$1" &>/dev/null || echo "$1" >>names.txt' none {} \;
This runs
identify
on each file and, ifidentify
returns a non-zero error code, it echoes the file name tonames.txt
.bash -c '...' none {}
causes a bash shell to run the command in the quotes with the file name in{}
assigned to positional argument$1
.For the curious, the string
none
is assigned to$0
.$0
is not used unless bash generates an error in which case it will appear in the error message as the program name.Discussion
The subtlety is that the
||
has to operate on theidentify
command. To do that, we need to putidentify
in a shell such as by usingbash -c
as shown above.