How to Check If a File is Empty in Bash [6 Methods]

An empty file in Bash refers to a file with no content or a size of zero bytes. In Bash scripting, while working with files, it’s very important to learn how to check if a file is empty or not. To check if a file is empty, you can go for several methods such as using the -s option, wc command, -z option, grep command, stat command, and ls command.

In the following article, I’ll show you 6 methods to check if a file is empty in Bash:

1. Using “-s” Flag With “[ ]” Construct

The “-s” flag within an ‘if’ conditional statement is used to check the size of a file. In this effort,  the single square brackets [ ] can be used to perform the test operation. However, if the file within the test expression has a size greater than zero, it means the file contains some value and is not empty. But when using the NOT (!) operator with the -s flag, it inverts the output and returns a true expression if the file is empty.

Go through the following script to check if a file is empty in Bash:

#!/bin/bash

file_path="/home/nadiba/color.txt"
if [ ! -s "$file_path" ]; then
echo "The file 'color.txt' is empty."
fi

EXPLANATION

In this script, if [ ! -s "$file_path" ]; verifies whether the file at the specified path is empty. If the file has a size of zero bytes, it returns a zero exit status meaning that the file is empty. Otherwise, it returns nothing.

Checking if a file is empty using the NOT (!) operator with the '-s' flag in Bash

This image states that the file color.txt in my system is empty.

Notes:

  1. Make sure to insert the spaces between the single square brackets [ ] and a semicolon (;) at the end of the brackets.

  2. The test operation can also be done using the “test” command which is equivalent to single square brackets [ ]. In that case, use the syntax if test ! -s "$file_path".

  3. The “-s” flag evaluates a file to empty only if it is newly created (it has zero size). However, it does not consider the presence of hidden characters or whitespace.

2. Using “wc” Command with “-c” Flag

The “wc (word count)” command with the “-c” flag within an if statement in Bash is used to count the number of bytes in a file. If the byte count is zero, it returns a true expression, meaning the file is empty. Otherwise, it returns nothing.

To learn how to check if a file is empty, use the wc -c command. Go through the following script:

#!/bin/bash

file_name=emoji.txt

#Checking if file has any lines
if [ $(wc -c < "${file_name}") -eq 0 ]; then
echo "'$file_name' is empty."
fi

EXPLANATION

In the script, wc -c < "${file_name}" counts the number of bytes in the file specified by the variable file_name. Here, the script uses the command substitution construct $( ) that captures the output of the wc command and checks if the byte count is equal to zero. If the byte count is zero, it implies that the file is empty.

Checking if a file is empty using 'wc -c' command in Bash

This image states that the file emoji.txt I have checked in my system is empty.

3. Using “-z” Flag

The “-z” option in Bash mainly checks if a string is empty. Using this -z option along the cat command is an effective way to check for an empty file (completely empty) i.e. the file that contains no lines or includes only whitespaces.

If you want to check for an empty file, use the -z option. Here is how:

#!/bin/bash

file_name=emoji.txt

if [ -z "$(cat ${file_name})" ]; then
echo "The file is empty."
fi

EXPLANATION

In the syntax if [ -z "$(cat ${file_name})" ];, the cat command reads the contents of the file emoji.txt and passes them to the test expression as a string. Then, the -z option checks if the length of the string is zero. If the file is empty, the cat command passes nothing, leading to an empty string that the -z option identifies.

Checking if a file is empty using the '-z' flag with the 'cat' command in Bash

In the image, you can see that the file emoji.txt in my system is empty.

4. Using “grep” Command with “-q” Flag

The grep command in Bash is generally used for pattern matching. However, it can be used with the -q flag to indirectly check if a file is empty or has any content.

Review the script below to check if a file is empty in Bash:

#!/bin/bash

file_name=example.txt

if ! grep -q . "${file_name}"; then
echo "'example.txt' is empty."
fi

EXPLANATION

In the syntax if ! grep -q . "${file_name}";, grep -q . "${file_name}" searches for any character in the specified file where the -q flag instructs grep to run quietly and ‘.’ indicates the regular expression that matches any character. The NOT (!) operator within the ‘if’ statement negates the output of the grep command and checks if grep does not find any character in the file. If grep does not find any character, it means the file is empty.

Checking if a file is empty using 'grep' command with the '-q' flag in Bash

From the image, you can see that the file example.txt in my system is empty.

Note: The “grep” command evaluates a file to empty whether it has zero size or contains only whitespace.

5. Using “stat” Command with “-c” Flag

The stat command is a utility in Bash that is used to retrieve information about files and filesystems. This command can be conjugated with the “-c” flag to display the size of the file in bytes. If a file size is zero bytes, the file is empty. Otherwise, it means that the file is not empty.

To check if a file is empty in Bash, use the stat -c command:

#!/bin/bash

filename=function.sh

if [ $(stat -c %s "${filename}") -eq 0 ]; then
echo "The file '$filename' is empty."
fi

EXPLANATION

Here, stat -c %s "$filename" retrieves the size of the specified file in bytes and stores it in the filename variable where stat -c specifies the format and %s represents the file size in bytes. Then, the ‘if’ conditional checks if the file size obtained from the stat command is equal to zero. If the file size is zero, it indicates the file is empty. Otherwise, it returns nothing.

Checking if a file is empty using 'stat' command with '-c' flag in Bash

This image dictates that the file function.sh in my system is empty.

6. Using “ls” Command

The ls command with the “-l” flag (long listing format) in Bash is used to display detailed information about files such as ownership, file size, permissions etc. This command can indirectly check if a file is empty in Bash by evaluating the size of that file. If the file has a size of zero bytes, it is considered an empty file.

Here’s how you can check if a file is empty in Bash using the ls -l command:

#!/bin/bash

file_name="abstract.txt"

#Getting the size of the file using ls -l and extracting the file size column
file_size=$(ls -l "$file_name" | awk '{print $5}')

#Checking if the file size is equal to zero
if [ "$file_size" -eq 0 ]; then
echo "The file '$file_name' is empty."
fi

EXPLANATION

The above script uses ls -l to get detailed information about the file abstract.txt, pipes the output to the awk command to extract the fifth column i.e. the file size column represented by $5 and then stores the size in file_size variable. After that, the syntax if [ "$file_size" -eq 0 ]; checks if the variable file_size is equal to zero. If the file size is zero, it returns true meaning that the file is empty. Otherwise, it returns nothing.

Checking if a file is empty using 'ls -l' command in Bash

From the image, you can see that the file abstract.txt in my system is empty.

Conclusion

As you can see, there are many ways to check if a file is empty in Bash, choose an appropriate one that suits your requirements. But before checking the emptiness of a file, make sure that it exists in your system.

People Also Ask

Can I perform a file emptiness check within a one-liner in Bash?

Yes, you can perform a file emptiness check within a one-liner in Bash by using the ‘-s’ flag with the [ ] construct. For example:

#!/bin/bash

if [ ! -s "file.txt" ]; then echo "The file is empty"; fi

Can I distinguish between an empty file and a non-existent file in Bash?

Yes, you can distinguish between an empty file and a non-existent file in Bash by performing different ‘if’ conditional tests using the syntaxes [ -s "FILENAME" ] and [ -e "FILENAME" ]. For Example:

#!/bin/bash

#Checking if the file exists
if [ -e "filename.txt" ]; then

#Checking if the file is empty
if [ -s "filename.txt" ]; then
echo "The file exists and is not empty."
else
echo "The file exists but is empty."
fi
else
echo The file does not exist."
fi

How can I handle cases where a file appears empty but contains whitespace or special characters?

To handle cases where a file appears empty but contains whitespaces (tabs, spaces or newlines) or special characters, you should consider the content of a file as well as the file size. Here’s how you can do so:

Checking for non-whitespace characters using the grep command:

#!/bin/bash

if grep -q '[^[:space:]]' "filename.txt"; then
echo "The file contains non-whitespace characters."
else
echo "The file is either empty or contains only whitespaces."
fi

Checking for files containing non-whitespace characters by trimming whitespaces and checking length:

#!/bin/bash

trimmed_file_content=$(< "filename.txt" tr -d '[:space:]')

if [ -n "$trimmed_file_content" ]; then
echo "The file contains non-whitespace characters."
else
echo "The file is either empty or contains only whitespaces."
fi

Are there implications for empty file detection in cross-platform Bash scripting?

Yes, cross-platform Bash scripting can have implications with empty file detection because of differences in behaviors, commands, and file system rules in different environments.

Can an empty file have metadata or attributes that distinguish it from non-empty files?

Yes, an empty file can have metadata or attributes that distinguish it from non-empty files. The file attributes that can distinguish empty files from non-empty ones are file size, and timestamps (creation time, modification time, and access time).

What’s the distinction between a file with zero bytes and an empty file containing whitespace characters?

A file with zero bytes is empty and contains no characters (including whitespaces). On the other hand, an empty file containing whitespace characters is not a zero-byte file and contains hidden characters.

Related Articles


<< Go Back to If Statement in Bash | Bash Conditional Statements | Bash Scripting Tutorial

Rate this post
LINUX
FUNDAMENTALS
A Complete Guide for Beginners Enroll Course Now
Nadiba Rahman

Hello, This is Nadiba Rahman, currently working as a Linux Content Developer Executive at SOFTEKO. I have completed my graduation with a bachelor’s degree in Electronics & Telecommunication Engineering from Rajshahi University of Engineering & Technology (RUET).I am quite passionate about crafting. I really adore exploring and learning new things which always helps me to think transparently. And this curiosity led me to pursue knowledge about Linux. My goal is to portray Linux-based practical problems and share them with you. Read Full Bio

Leave a Comment