Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

linux

bash

png

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!

like image 300
Bean Taxi Avatar asked Jan 29 '16 20:01

Bean Taxi


People also ask

How do I open a PNG file in Linux command line?

For terminal users, feh is a great tool to view PNG files. It is a lightweight and straightforward tool that uses command-line arguments. Feh will launch the image and window size respective to the image size.

What is E flag in bash?

The -e flag instructs the script to exit on error. More flags. If there is an error it will exit right away. The $? is the exit status of the last command.


2 Answers

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
like image 142
Arkadiusz Drabczyk Avatar answered Oct 05 '22 21:10

Arkadiusz Drabczyk


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
like image 34
PBI Avatar answered Oct 05 '22 21:10

PBI