9

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
5
  • 3
    If the file have space characters in it, it's not empty, is it?
    – Kusalananda
    Aug 16, 2017 at 18:16
  • empty include blank spaces for my task
    – yael
    Aug 16, 2017 at 18:18
  • cat $file | tr -s " " > $file; [ ! -s $file ] && echo "hello there I am empty file !!!"
    – jesse_b
    Aug 16, 2017 at 18:19
  • 2
    @Jesse_b I'm pretty sure that would truncate the file before even executing cat...
    – Kusalananda
    Aug 16, 2017 at 18:21
  • In that case I should be able to do just: tr -s " " > $file; [ ! -s $file ] && echo "hello there I am empty file !!!" no? Either way the command with cat works and doesn't without.
    – jesse_b
    Aug 16, 2017 at 19:07

3 Answers 3

26

Just grep for a character other than space:

grep -q '[^[:space:]]' < "$file" &&
  printf '%s\n' "$file contains something else than whitespace characters"
0
5

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
-1

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'

3
  • 1
    This solves an issue that user in the question does not have.
    – Kusalananda
    Aug 8, 2019 at 15:59
  • Thanks @Kusalananda, I've added this answer, as people might find it useful when using square brackets around the grep condition.
    – Noam Manos
    Aug 8, 2019 at 16:20
  • 1
    It's just if grep -q '[^[:space:]]' $file. The [[ are not part of the if syntax, they are a command that returns status according to some condition. You are already checking status, so you should have just if grep -q …
    – Jan Hudec
    Jul 1, 2020 at 15:25

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .