How to check if the file is empty or has blank space.?

Hi,

I am using KSH.
I am trying to check if the output file is empty or not.
I tried with

[[ -s $file ]] 

but what i see is my file is empty but still manages to have a size of 1 instead of 0.

But my file doesnot have anything its empty.

I am not sure how to check this.
can any one help?

What does the output from ls -l filename give you?

If the size really is 1, then this test will say that it has data and therefore is not empty. Have a look at the manual pages for test for more details.

How do you create/empty the file?

Robin

one case could be
If you write some content and delete that, the file has a size 1
do a wc on the file wc $file

An empty file will show a size of 0.

However, it depends what (script?) wrote the file and whether it placed a single character (eg, a carriage return or some other unprintable character) in the file before closing it.

Can you use a hex editor or the like to see what that one character really is?

You are correct i am getting some data and deleting it so its coming as 1 while the file is empty.

Can't we do anything about it??

Are you sure it is not a newline character?

For example echo "" > filename is effectively an empty file but has a file length of '1'...

hexdump -C < /path/to/filename will show the hex character...

---------- Post updated at 03:52 PM ---------- Previous update was at 03:49 PM ----------

How about > /path/to/filename ?

if (file exist) {
do whatever
extract data from file
delete file
touch file
}
done

We can, open the file with vi and delete the line, type dd and save the file

How about:

if [ $(tr -d ' \r\n\t' < filename | wc -c ) -eq 0 ]
then
        echo "File is empty"
else
        echo "File has non-blank characters"
fi
read x1 < $file
[[ -z "$x1" ]]

This tests the first line.
Or

awk 'NF {exit 1}' $file
[[ $? -eq 0 ]]

Thanks alot!! :smiley: it is working now.. :slight_smile: