Bash: How to Check if File Size is Greater than Zero


Often you may want to check if the size of a particular file is greater than zero in Bash.

You can use the following syntax to do so:

file_size=$(stat -c%s "c:/users/bobbi/data2/players.txt")

if (( file_size > 0 ))
then
    echo "File size greater than zero"
else
    echo "File size not greater than zero"
fi

This particular example finds the file size (in bytes) of a file named players.txt and stores the results in a variable named file_size.

We then use an if else statement to check if the value of file_size is greater than zero and return one of the following strings as a result:

  • “File size greater than zero”
  • “File size not greater than zero”

The following example shows how to use this syntax in practice.

Example: How to Check if File Size is Greater than Zero in Bash

Suppose that we have a file named players.txt located at the following path on our computer:

  • c:/users/bobbi/data2/players.txt

We can use the following syntax to first display the size of this file:

file_size=$(stat -c%s "c:/users/bobbi/data2/players.txt")

echo $file_size

The following screenshot shows how to use this syntax in practice:

From the output we can see that the file has a size of 122 bytes.

We can then use the following syntax to check if this file size is greater than zero:

if (( file_size > 0 ))
then
    echo "File size greater than zero"
else
    echo "File size not greater than zero"
fi

The following screenshot shows how to use this syntax in practice:

Bash check if file size greater than zero

The output returns “File size greater than zero” since the file size is indeed greater than zero.

Note: Feel free to replace 0 in the if statement with a different number to instead check if the file is greater than a different size.

Related Tutorials

The following tutorials explain how to perform other common tasks in Bash:

Bash: How to Delete All Empty Lines in File
Bash: How to Check if File Contains Specific String
Bash: How to Print Specific Range of Lines from File

Leave a Reply