Is there a quick way to check if a gzipped file is empty, or do I have to unzip it first?
example:
$ touch foo
$ if [ -s foo ]; then echo not empty; fi
$ gzip foo
$ if [ -s foo.gz ]; then echo not empty; fi
not empty
$ wc -l foo.gz
1 foo.gz
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems. It only takes a minute to sign up.
Sign up to join this communitygzip -l foo.gz | awk 'NR==2 {print $2}'
prints the size of the uncompressed data.
if LC_ALL=C gzip -l foo.gz | awk 'NR==2 {exit($2!=0)}'; then
echo foo is empty
else
echo foo is not empty
fi
Alternatively you can start uncompressing the data.
if [ -n "$(gunzip <foo.gz | head -c 1 | tr '\0\n' __)" ]; then
echo "foo is not empty"
else
echo "foo is empty"
fi
(If your system doesn't have head -c
to extract the first byte, use head -n 1
to extract the first line instead.)
LC_ALL=C
is there to ensure that gzip does not put in thousand separators in numbers so the field can be compared to zero?
LC_ALL=C
can't hurt.
Feb 1, 2011 at 23:44
read
is being invoked in a subshell (and $line
is not propagated to the parent).
Sep 8, 2012 at 0:15
tr
fixes that.
Sep 8, 2012 at 11:44
If by 'empty' you mean that the uncompressed file is 0 bytes, you could use gzip --list foo.gz
to determine the size of the uncompressed file, it would require some parsing to automate it. It looks something like this:
$ gzip --list foo.gz
compressed uncompressed ratio uncompressed_name
24 0 0.0% foo
test -z $(gzip -cd foo.gz | head -c1) && echo "empty"
Or with if
:
if [ -z $(gzip -cd foo.gz | head -c1) ]; then
echo "empty"
fi
zcat
is sometimes linked to gunzip -c
or gzip -cd
, if you want to use it as the shorter "form".
Please note that the gzip file format only allows 32 bits for storing the original file size, so the number there is the size modulo 2^32. Hence the size given by "gzip -l" is not a definitive test for emptiness.
If the gzip file size is 51, it is empty. Whenever I added a char in a file and gzip the file, zipped file size begins to increase from 51.
However you can guarantee it with zcat. in gzip man:
The uncompressed size is given as -1 for files not in gzip format, such as compressed .Z files. To get the uncompressed size for such a file, you can use:
zcat file.Z | wc -c