How to check if a large file contains only zero bytes ('\0'
) in Linux using a shell command? I can write a small program for this but this seems to be an overkill.
You can use the find command and other options as follows. The -s option to the test builtin check to see if FILE exists and has a size greater than zero. It returns true and false values to indicate that file is empty or has some data.
If you just want to get a list of zero byte sized files, remove the -exec and -delete options. This will cause find to print out the list of empty files.
$? is the exit status of the most recently-executed command; by convention, 0 means success and anything else indicates failure. That line is testing whether the grep command succeeded. The grep manpage states: The exit status is 0 if selected lines are found, and 1 if not found.
If you're using bash, you can use read -n 1
to exit early if a non-NUL
character has been found:
<your_file tr -d '\0' | read -n 1 || echo "All zeroes."
where you substitute the actual filename for your_file
.
The "file" /dev/zero
returns a sequence of zero bytes on read, so a cmp file /dev/zero
should give essentially what you want (reporting the first different byte just beyond the length of file
).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With