≡ Menu

Linux / UNIX: Check If File Is Empty Or Not Using Shell Script

How do I check if file is empty or not using bash or ksh shell script under UNIX / Linux / OS X / BSD operating systems?

You can use the find command as follows. The -s option to the test builtin check to see if FILE exists and has a size greater than zero. It returns true and false values to indicate that file is empty or has some data.

touch /tmp/file1
ls -l /tmp/file1
find /tmp -empty -name file1

Sample outputs:


Now create another file with some data in it:

echo "data" > /tmp/file2
ls -l /tmp/file2
find /tmp -empty -name file2

You should not see any output.

Shell -s option

However, use can pass -s option as follows in script or shell prompt:

touch /tmp/f1
echo "data" >/tmp/f2
ls -l /tmp/f{1,2}
[ -s /tmp/f1 ] 
echo $?

Sample outputs:


The non zero output indicate that file is empty.

[ -s /tmp/f2 ]
echo $?

Sample outputs:


The zero output indicate that file is not empty. So you can write a shell script as follows:

Shell Script To Check If File Is Empty OR Not

[ $# -eq 0 ] && { echo "Usage: $0 filename"; exit 1; }
[ ! -f "$_file" ] && { echo "Error: $0 file not found."; exit 2; }
if [ -s "$_file" ] 
	echo "$_file has some data."
        # do something as file has data
	echo "$_file is empty."
        # do something as file is empty 

Run it as follows:
chmod +x script.sh
./script.sh /etc/resolv.conf

Sample outputs:

/etc/resolv.conf has some data.

Run it on an empty file:
touch /tmp/test.txt
./script.sh /tmp/test.txt

Sample outputs:

test.txt is empty.
Share this tutorial on:

Like this? Follow us on Twitter OR support us by using Patreon

{ 6 comments… add one }
  • Ankit July 14, 2011, 1:13 pm

    Given shell script is not executing the then block of the if condition………….it always executing else block, either input file is empty or not…………..

  • raj March 14, 2012, 4:57 pm

    Very helpful …

  • Vivan April 27, 2012, 12:56 pm

    What if you there might be multiple files exist? ex:

    file1, file2, file3

    if [ -s “$file*” ] or if [-s file*]
    do not work
    any suggestions?


  • nixCraft July 9, 2012, 8:14 pm


    You need to edit the script:

    [ $# -eq 0 ] && { echo "Usage: $0 file1 file2 fileN"; exit 1; }
    for _file in $@
    [ ! -f "$_file" ] && { echo "Error: $_file file not found."; continue; } 
    if [ -s "$_file" ]
    	echo "$_file has some data."
            # do something as file has data
    	echo "$_file is empty."
            # do something as file is empty 
  • gof September 26, 2012, 12:44 pm

    How do send emails on the sample outputs in linux as a crontab

  • Kevin September 4, 2016, 9:03 pm

    This was very helpful, I have it in a script to email me when there are failed login attempts on my servers!

Security: Are you a robot or human?

Leave a Comment

You can use these HTML tags and attributes: <strong> <em> <pre> <code> <a href="" title="">

   Tagged with: , , , , , , , , , , , , , , , ,