Bash: How to Check if File is Empty (With Examples)


Often you may want to check if a particular file is empty using Bash.

You can use the following syntax to do so:

[[ -s player_info.txt ]] && echo "File is not empty" || echo "File is empty"

This particular example will check if the file named player_info.txt is empty and will output the appropriate response.

Note that we use the -s command to check if the size of the file is greater than zero, which is a simple way to check if there is any content in the file.

If you’d like, you can use the following syntax to return all files in the current directory that are empty:

for file in *.txt; do if [ ! -s $file ]; then echo $file; fi; done

This particular example will return all .txt files in the current directory that are empty.

The following examples show how to use each of these methods in practice.

Example 1: Check if File is Empty Using Bash

Suppose that we have a file named player_info.txt in our current directory and we would like to check if it is empty.

We can use the following syntax to do so:

[[ -s player_info.txt ]] && echo "File is not empty" || echo "File is empty"

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

Bash check if file is empty

This returns “File is not empty”, which indicates that the file has contents.

To view the contents of the file, we can use the cat command:

We can see that the file does indeed contain several lines with information about various basketball players.

Example 2: Display All Empty Files in Directory Using Bash

Suppose that we would like to find all empty .txt files in the current directory.

We can use the following syntax to do so:

for file in *.txt; do if [ ! -s $file ]; then echo $file; fi; done 

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

Bash find all empty files in directory

From the output we can see that there are two empty files in the current directory:

  • coaches_info.txt
  • team_info.txt

Note that we used the syntax ! -s $file to indicate that we’d like to display each file in the directory that does not have a size, i.e. does not have any content.

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 Replace Special Characters in String
Bash: How to Replace Multiple Characters in String

Leave a Reply