How to check in a Bash script, if a file is empty

To check if a file is empty in a Bash script, you can use the "-s" test, which returns true if the file exists and has a size greater than zero. If you want to check if a file is empty, you would use the "!" (not or negate) operator with "-s" to negate the test. Here's a script to demonstrate this:

#!/bin/bash

# Path to the file
FILE="path_to_your_file.txt"

# Check if the file exists and is empty
if [ -e "$FILE" ] && [ ! -s "$FILE" ]; then
    echo "The file exists and is empty."
elif [ ! -e "$FILE" ]; then
    echo "The file does not exist."
else
    echo "The file exists and is not empty."
fi

So, what is this script doing?

The code [ -e "$FILE" ] checks if the file exists, then [ ! -s "$FILE" ] checks if the file is not of size greater than zero (i.e., it is empty). The "elif" (else if) part handles the case where the file does not exist. And finally the "else" section covers the scenario where the file exists and is not empty.

Replace path_to_your_file.txt with the actual path to the file you want to check.

Leave a Comment