How to check if a file is empty?

QuestionsQuestions8 SkillsProPermissions of FilesOct, 29 2025
0143

To check if a file is empty in a Linux environment, you can use the -s option with the test command or the bracket syntax. Here’s how you can do it:

Using the test Command

You can use the test command with the -s option to check if a file is not empty:

test -s filename.txt && echo "File is not empty." || echo "File is empty."

Using Bracket Syntax

Alternatively, you can use the bracket syntax in a shell script:

if [ -s filename.txt ]; then
    echo "File is not empty."
else
    echo "File is empty."
fi

Explanation

  • -s filename.txt: Checks if the file filename.txt exists and has a size greater than zero (i.e., it is not empty).
  • &&: Executes the command following it if the previous command is true (file is not empty).
  • ||: Executes the command following it if the previous command is false (file is empty).

Example Script

Here’s a simple script that checks if a file is empty:

#!/bin/bash
FILENAME="example.txt"

if [ -s "$FILENAME" ]; then
    echo "File $FILENAME is not empty."
else
    echo "File $FILENAME is empty."
fi

Running the Script

  1. Save the script to a file, e.g., check_empty_file.sh.
  2. Make it executable:
    chmod +x check_empty_file.sh
  3. Run the script:
    ./check_empty_file.sh

This script will check if example.txt is empty and print the appropriate message.

Additional Method

You can also check the file size using the stat command:

if [ $(stat -c%s "filename.txt") -eq 0 ]; then
    echo "File is empty."
else
    echo "File is not empty."
fi

This method retrieves the file size and checks if it equals zero.

Feel free to ask if you have any further questions or need more examples!

0 Comments

no data
Be the first to share your comment!