Bash脚本检查zip文件是否为空

时间:2016-08-07 12:26:27

标签: linux bash

我对linux很缺乏经验, 如果某个zip文件为空,我必须检查bash脚本 - 因为zip不包含任何文件。 我找到了这段代码:

if ! zipinfo ${filetotransfer} | tail -n 1 | grep '^0 ' >/dev/null ; then # we have empty zip file!
   echo " zip empty"
   rm $filetotransfer
   exit 0
fi

但如果zip为空,它会删除文件。 有没有办法检查它?

2 个答案:

答案 0 :(得分:3)

您只需使用stat或md5sum或zip标题检查文件大小为22

# by checking file size
% stat -f%z a.zip 
22

% xxd a.zip
0000000: 504b 0506 0000 0000 0000 0000 0000 0000  PK..............
0000010: 0000 0000 0000                           ......

# with md5sum
$ md5sum a.zip
76cdb2bad9582d23c1f6f4d868218d6c  a.zip

# or by checking zip header
% [ `head -n22 a.zip | tr -d '\0-\6'` = "PK" ] && echo 1
1

答案 1 :(得分:1)

您可以查看zipinfo -t

的错误状态
f=test.zip
if zipinfo -t "$f" > /dev/null
then
    echo "not empy"
else
    echo "empty"
fi