5

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
  • 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
14

Just grep for a character other than space:

grep -q '[^[:space:]]' < "$file" &&
  printf '%s\n' "$file contains something else than whitespace characters"
  • 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

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.