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
Just grep
for a character other than space:
grep -q '[^[:space:]]' < "$file" &&
printf '%sn' "$file contains something else than whitespace characters"
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’
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
if grep -q ‘[^[:space:]]’ $file.