How to check if zip file is empty in bash

5,084

Solution 1

If you have the Info-ZIP tools installed (zip, unzip, zipinfo) you can use zipinfo on the zip file and just send the output to /dev/null. The status will be 0 if the file is not empty.

So:

if zipinfo foo.zip > /dev/null; then
    echo not empty
else
    echo empty
fi

Solution 2

If you run zipinfo -t foo.zip the exit status (from $?)will give an error if the zip file has nothing in it. In the version I'm running (3.00) this will be 1 but I imagine that's just a general error code, so the ambiguity might cause you other problems.

You'll also have to deal with the text output of the command which is a string with basic info about the file. I believe this answer is similar to one of those above.

Edit: If you want to avoid the ambiguous return value (and you're in the mood for grep) you could grep the output of the above command for "Empty zipfile".

Share:
5,084

Related videos on Youtube

CBR
Author by

CBR

Updated on September 18, 2022

Comments

  • CBR
    CBR over 1 year

    How can I verify if the zip file is empty or not ? I cannot use if -s in bash as the zip file is not always zero in size. if the zip file has empty directories in it, I want to delete the file else extract the file.

  • SeanJ
    SeanJ almost 12 years
    is it possible with pure bash scripting without even using java jar ?
  • Tim Pote
    Tim Pote almost 12 years
    @nlrreddy See my edits.
  • Admin
    Admin almost 12 years
    this was giving me the same return code but I tweaked the above a little bit. add | grep ^- to look for files and then delete the file if $? is 1. Thank you Laurence
  • Tim Pote
    Tim Pote almost 12 years
    +1 I'd never heard of zipinfo before. @nlrreddy If Laurence solved your issue, feel free to accept his answer by clicking the checkmark on the left.
  • JFK
    JFK almost 3 years
    zipinfo can potentially fail with exit code 1 for other reasons than an empty zip file. If you just look for exit code 1 you are in for trouble.