LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Linux - Software (https://www.linuxquestions.org/questions/linux-software-2/)
-   -   How can I make my script check to see if a file is empty? (https://www.linuxquestions.org/questions/linux-software-2/how-can-i-make-my-script-check-to-see-if-a-file-is-empty-398333/)

spiffytech 01-01-2006 07:39 AM

How can I make my script check to see if a file is empty?
 
I need to make my script check to see if a text file is empty so I can fork the process depending on whether or not it is. How do I do that?

homey 01-01-2006 08:20 AM

Something like this...
Code:

#!/bin/bash
# Example: ./test file.txt

fsize=$(stat -c %s $1)

if [ $fsize -lt 1 ] ; then
  echo $1 is empty
  else
  echo $1 is not empty
fi


LiNuXkOlOnIe 01-01-2006 08:31 AM

Quote:

Originally Posted by homey
Something like this...
Code:

#!/bin/bash
# Example: ./test file.txt

fsize=`stat -c %s $1`

if [ $fsize -lt 1 ] ; then
  echo $1 is empty
  else
  echo $1 is not empty
fi


The new way of command-substitution and recommended is:
fsize = $(stat -c %s $1)

The result of both is the same. Not an advise only how i make it cos the backtick could be overseen in an hot programming session.

Happy new year.

homey 01-01-2006 08:38 AM

Thanks for the tip LiNuXkOlOnIe ! :)

jcliburn 01-01-2006 09:08 AM

Bash has a built-in test for this and many other file attributes (see the bash manpage). The "-s" option tests for a file with non-zero size.

Code:

#!/bin/bash

if [ -s $1 ]; then
        echo "File size is non-zero";
else
        echo "File size is zero";
fi


LiNuXkOlOnIe 01-01-2006 09:12 AM

Jaaauu. And the oscar goes tooo ...
jcliburn.

thank you.

Don't worry only spamming. :-)))

jcliburn 01-01-2006 09:35 AM

One caveat with the -s method... It returns false under TWO conditions: the file size is zero, OR if the file doesn't exist. So if you feed my sample script a nonexistent file name, it'll say "File size is zero".


All times are GMT -5. The time now is 03:52 PM.