Bean Taxi
Bean Taxi

Reputation: 1261

Easy one-liner for bash/linux, to check if a PNG is valid?

pngcheck is almost perfect. But in its simplest form, pngcheck outputs a line beginning with either OK: or ERROR:. This means I have to parse an output string, and I would rather just check a return value.

I looked at the pngcheck.c source code, and a thorough check for PNG validity is quite the ordeal - much more than just a magic number check. So the best I can do at the moment, is to create a simple pngcheck.sh which calls pngcheck and parses the output string, followed by exit 0 or exit 1 accordingly.

But I wanted to check if there is an easy or more 'bashonic' solution.

Thanks!

Upvotes: 7

Views: 3373

Answers (2)

PBI
PBI

Reputation: 335

When I look in the source code of pngcheck.c (PNGcheck, version 2.3.0 of 7 July 2007), I believe it does set the return code. Near the end of main( ):

717   if (num_errors > 0)
718     err = (num_errors > 127)? 127 : (num_errors < 2)? 2 : num_errors;
719   else if (num_warnings > 0)
720     err = 1;
...

num_errors is the number of files that failed, num_warnings is the number of files that had a warning. Then it exits with "return err;"

So the return code is 0 for all ok, 1 for warnings only, and 2 or higher is the number of files that failed (max 127).

And that is also consistent with the small test I did on the binary installed on Ubuntu.

pngcheck -q /etc/profile >/dev/null; echo $?    # returns 2
pngcheck -q cpu50.png >/dev/null;  echo $?      # returns 0

Upvotes: 4

Arkadiusz Drabczyk
Arkadiusz Drabczyk

Reputation: 12518

After looking at the source code I think that you can just use $? that holds exit status of the previous command in many shells. See line 4684 in pngcheck.c where success message is printed. If there was error global_error wouldn't be set to 0 and would be passed to and returnd by main(). Things got easy now:

#!/usr/bin/env sh

if pngcheck "$1" > /dev/null 2>&1
then
    echo things went ok
else
    echo things went bad
fi

Usage:

$ ./check-png.sh /usr/share/icons/HighContrast/22x22/status/touchpad-disabled.png
things went ok
$ ./check-png.sh /tmp/FILE
things went bad

Upvotes: 7

Related Questions