6

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 '17 at 18:16
  • empty include blank spaces for my task
    – yael
    Aug 16 '17 at 18:18
  • cat $file | tr -s " " > $file; [ ! -s $file ] && echo "hello there I am empty file !!!"
    – jesse_b
    Aug 16 '17 at 18:19
  • 2
    @Jesse_b I'm pretty sure that would truncate the file before even executing cat...
    – Kusalananda
    Aug 16 '17 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 '17 at 19:07
19

Just grep for a character other than space:

grep -q '[^[:space:]]' < "$file" &&
  printf '%s\n' "$file contains something else than whitespace characters"
3
  • echo "Non empty string" | grep -q '[^[:space:]]' fails because it contains spaces even though it isn't empty
    – AFP_555
    Aug 26 '18 at 11:01
  • I don't get it, @AFP_555: what do you mean by "fails"? echo "Non empty string" | grep -q '[^[:space:]]' is your command, not mine. Put "Non empty string" in a file and try my command.
    – xhienne
    Aug 26 '18 at 11:09
  • Oh, sorry about that! Got confused with the &&
    – AFP_555
    Aug 26 '18 at 11:14
1

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 '19 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 '19 at 16:20
  • 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 '20 at 15:25

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.