Bash: test both file existence and size to avoid signalling success

A Bash script can often run into the situation where a utility in the pipeline creates a file, but because of an unexpected error, the size of the resulting file is zero bytes.

And if that situation is not prepared for, the mere existence of the file might signal success to the following commands in the script.  Below is an example of testing just for file existence with the “-f” test.

tempfile=$(mktemp)
[ -f $tempfile ] || echo "File $tempfile does not exist"

And here is an example of testing for both existence and non-zero size with the “-s” test.

[ -s $tempfile ] || echo "File $tempfile does not exist or is 0 bytes"

Alternative implementations

They are more verbose, but one could use ‘stat‘ or ‘find‘ to implement the same test.

filesize=$(stat -c%s $tempfile)
if [[ -f $tempfile && $filesize -gt 0 ]]; then
  echo "longer form of validating file existence and size of $tempfile at $filesize bytes"
fi

find $tempfile -size +0b 2>/dev/null | grep .
if [[ $? -eq 0 ]]; then
  echo "'find' validated both file existence and size of $tempfile"
fi

A full example can be found at file_existence_and_size.sh

REFERENCES

linux man page for test

NOTES

Another way to force immediate failure in Bash pipeline, which can avoid errors being processed as valid.

set -euo pipefile