LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (http://www.linuxquestions.org/questions/programming-9/)
-   -   shell script to determine if file size equals zero (http://www.linuxquestions.org/questions/programming-9/shell-script-to-determine-if-file-size-equals-zero-606104/)

jonfa 12-11-2007 02:27 PM

shell script to determine if file size equals zero
 
Hi All,

I am attempting to write a shell script to determine if a particular file has a size of zero or not. here is my script:

#!/bin/sh

myfilesize=`exec ls -ld file.txt | awk '{ s+=$5 }'`
if [ "$myfilesize = 0" ];then
echo "the file size is zero"
else
echo "the file size is NOT zero"
fi
exit 0


Any ideas on why it doesn't work?

acid_kewpie 12-11-2007 02:35 PM

just use the -s option to test. much much simpler...

if [ -s $file ]
then
echo yes
else
echo no
fi

don't reinvent the wheel. as for what's wrong... quite a few things to be honest, you're test doens't make sense as the entire thing is in quote marks, meaning that it'll always be "true" as if you just provide a string it is true if the string has a length, false if it's null.

MicahCarrick 12-11-2007 02:35 PM

This will work:
Code:

#!/bin/bash

myfilesize=`stat -c %s file.txt`
if [ $myfilesize = 0 ];then
echo "the file size is zero"
else
echo "the file size is NOT zero"
fi
exit 0


pixellany 12-11-2007 02:46 PM

Quote:

Any ideas on why it doesn't work?
Yes.....the syntax is wrong.

ls -ld looks only for directories

What is this supposed to do?
Code:

awk '{ s+=$5 }'

jonfa 12-11-2007 02:47 PM

Quote:

Originally Posted by MicahCarrick (Post 2987467)
This will work:
Code:

#!/bin/bash

myfilesize=`stat -c %s file.txt`
if [ $myfilesize = 0 ];then
echo "the file size is zero"
else
echo "the file size is NOT zero"
fi
exit 0


Thank you...that worked. I do have another question. I see you used the "stat" command. I have this on my linux box, but not on my solaris 10 box. Is there another command I could substitute?

chrism01 12-11-2007 04:48 PM

Use acid_kewpie's answer; like he said, don't re-invent the wheel.
See : http://www.tldp.org/LDP/abs/html/fto.html


All times are GMT -5. The time now is 08:44 PM.