Page 1 of 1

Trying to use identify to examine if an image is valid

Posted: 2013-12-07T11:36:30-07:00
by jamadagni
Hello. I tried writing something similar to the following minimal testcase to test using identify if a file (if it exists) is a valid image or not, and if yes, to move it to a particular location:

Code: Select all

#! /bin/sh
ifile=input.jpg
identify $ifile &> /dev/null && {
        echo "DEBUG: moving the jpg"
        mv -v $ifile foo.jpg
} || {
        rm $ifile
        echo "Input file not a valid image"
}
However it is failing with the following session transcript illustrating the curious failure:

Code: Select all

$ ls
im-test.sh
$ ./im-test.sh 
DEBUG: moving the jpg
mv: cannot stat ‘input.jpg’: No such file or directory
rm: cannot remove ‘input.jpg’: No such file or directory
Input file not a valid image
$ identify.im6: unable to open image `input.jpg': No such file or directory @ error/blob.c/OpenBlob/2638.
^C
$
$ touch input.jpg
$ ./im-test.sh 
DEBUG: moving the jpg
‘input.jpg’ -> ‘foo.jpg’
$ identify.im6: unable to open image `input.jpg': No such file or directory @ error/blob.c/OpenBlob/2638.
^C
$
$ identify -version
Version: ImageMagick 6.7.7-10 2013-09-10 Q16 http://www.imagemagick.org
Copyright: Copyright (C) 1999-2012 ImageMagick Studio LLC
Features: OpenMP
I totally do not understand how identify is apparently returning a success exit status so that the && part of the script is executing, but actually identify is apparently trying to examine the image *after* the && part has moved the image elsewhere!

This is mucking up the behaviour of my script. Please help!

Re: Trying to use identify to examine if an image is valid

Posted: 2013-12-07T21:01:38-07:00
by snibgo
I'm not a bash scripter, but your script looks strange to me. I assume "&&" has higher precedence than "||". "identify" returns 1 for failure or 0 for success. Your expression interpreter tries to make both sides of && true, ie 1. So the mv will be tried only if identify fails.

But I could be wrong about this.

Re: Trying to use identify to examine if an image is valid

Posted: 2013-12-07T23:09:41-07:00
by jamadagni
Hi thanks for your reply snibgo.

I found out that the problem was that I was using sh and not bash in my script. sh (which is symlinked to dash on my Ubuntu system) does not recognize the &> operator to redirect both stderr and stdout. I figured this out at unix.stackexchange. If I change the script to use /bin/bash at the shebang line, all is fine.

Thanks anyhow for replying.