Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if a file contains only zeros in a Linux shell?

Tags:

file

linux

shell

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.

like image 819
vitaut Avatar asked Nov 26 '13 18:11

vitaut


People also ask

How do I check if a file is zero byte in Unix?

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.

How do you find a zero byte file?

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.

What is $? 0 in shell script?

$? 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.


2 Answers

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.

like image 165
user2719058 Avatar answered Oct 12 '22 11:10

user2719058


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).

like image 35
vonbrand Avatar answered Oct 12 '22 09:10

vonbrand