Linux / UNIX: Check If File Is Empty Or Not Using Shell Script

To check if a file is empty or not using a shell script in Linux or UNIX, you can use the test command with the -s option, which checks if the file is non-empty. Here’s an example shell script that checks if a file is empty or not:

#!/bin/bash

if [ -s "/path/to/file" ]
then
echo "The file is not empty."
else
echo "The file is empty."
fi

In this script, replace /path/to/file with the path to the file you want to check. The test command with the -s option returns true if the file is non-empty, and false if the file is empty. The if statement checks the result of the test command and prints a message indicating whether the file is empty or not.

You can also use the wc command to count the number of lines, words, and characters in a file, and check if the line count is zero. Here’s an example script that uses wc to check if a file is empty or not:

#!/bin/bash

if [ $(wc -l < "/path/to/file") -eq 0 ]
then
echo "The file is empty."
else
echo "The file is not empty."
fi

In this script, the wc -l command counts the number of lines in the file, and the output is piped to the if statement, which checks if the line count is zero. If the line count is zero, the script prints a message indicating that the file is empty. Otherwise, it prints a message indicating that the file is not empty.

Leave a Comment