How to check if file is empty or it has only blank characters?

This will notify us if the file is empty:

[[ ! -s $file ]] && echo "hello there I am empty file !!!"

But how to check if a file has blank spaces (spaces or tabs)?

  • empty file can include empty spaces / TAB
Asked By: yael

||

Just grep for a character other than space:

grep -q '[^[:space:]]' < "$file" &&
  printf '%sn' "$file contains something else than whitespace characters"
Answered By: xhienne

If you want to check for empty file content within an if condition [[ ... ]], then surround the grep with -z $( grep ... ) (without -q):

if [[ -z $(grep '[^[:space:]]' $file) ]] ; then
  echo "Empty file" 
  ...
fi

I had to use this, in order to avoid following error when running:

$ [[ grep -q '[^[:space:]]' $file ]]

-bash: conditional binary operator expected

-bash: syntax error near `-q’

Answered By: Noam Manos

Similar to the other answers but using a negated grep -q

if ! grep -q '[^[:space:]]' "$file"; then
    echo "file is empty"
else
    echo "File has data"
fi
Answered By: steveH

if grep -q ‘[^[:space:]]’ $file.

Answered By: Arpita
Categories: Answers Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.