check if file is empty

How do I check if a file is empty in a sh script

I want to test in my shell script if the output file is empty and if it is do one thing and if it isnt empty do another?

any ideas?

Read the man pages of test

       -s FILE
              FILE exists and has a size greater than zero

Within a script it would take this form.

#! /bin/ksh

if [[ -s $FILE ]] ; then
echo "$FILE has data."
else
echo "$FILE is empty."
fi ;

vino

an exit status of 1 indicates that the FILE is empty or the file does not exist.....

$ ls
$ touch file_1
$ dd if=/dev/zero of=$HOME/tmp/file_2 bs=1 count=100
100+0 records in
100+0 records out
$ ls -l file_1 file_2 file_3
ls: file_3: No such file or directory
-rw-rw-r--  1 foo bar   0 Sep 24 20:28 file_1
-rw-rw-r--  1 foo bar 100 Sep 24 20:28 file_2
$ [[ -s file_1 ]]
$ echo $?
1
$ [[ -s file_2 ]]
$ echo $?
0
$ [[ -s file_3 ]]
$ echo $?
1

Cheers
ZB

A sleek 'n' smart solution !! :cool:

this is just another way of doing it

a round about one

if [ `ls -l <file> | awk '{print $5}'` -eq 0 ]
then
//condition for being empty
else
//condition for not being empty
fi

better way of doing is using the -s option of test

All worked as I required -s FILE option was the solution I used in my script and now I am a happy man.

I have a requirement where if file size is 487 then ignore it otherwise put into e-mail script? I can do it using -s but it does only if file is empty...
any clue on this please???

FILE="path of your file"
FILESIZE="`du -b $FILE | sed 's:^\([0-9]*\)*[[:space:]]*.*:\1:'`" 

if [ "$FILESIZE" = "487" ];then
 echo "$FILE has size 487 bytes"
else
 echo "Some other filesize"
fi

In place of '=' you can use '-gt' '-lt' '-gte' '-lte' for greater than, less than, greater than or equal to, less than or equal to.

The -b option to du is not standard. The usual command to use is wc:

filesize=$( wc -c < "$FILE" )

It's -le not -lte, and -ge not -gte.