In shell or bash scripting, it is often necessary to check if a file exists and whether it is empty. This is especially important when dealing with input/output operations or when performing actions based on the contents of a file. In this article, we will discuss how to check if a file exists and is empty or not so read this guide if you are looking for an easy way to do it.
How to Check if File exists and is Empty in Bash
When working with shell scripts, it’s important to be able to check if a file exists and if it’s empty or not. This is especially useful when automating tasks that rely on specific files being present and non-empty, here is an example that illustrate how to check if the file exists and is empty:
filename="bashfile.sh"
size_threshold=1
# Check if file exists
if [ -e "$filename" ]
then
# Get file size in bytes
file_size=$(wc -c < "$filename")
# Check if file is empty
if [ "$file_size" -gt "$size_threshold" ]
then
echo "File exists and is not empty"
else
echo "File exists but is empty"
fi
else
echo "File does not exist"
fi
In this bash script example, we first set the filename, the size_threshold variable and then check if any file exists with the given name using the -e option. If it exists, we use the wc command to get the file size in bytes and store it in the file_size variable.
Next, we check if the file is empty by comparing the file_size to the size_threshold. If the file is larger than the threshold, we output a message indicating that the file exists and is not empty. Otherwise, we output a message indicating that the file exists but is empty.
By setting a size threshold, you can customize the script to check if the file is empty based on your specific needs.
Since the file I am checking is empty, the bash script will show that the file is empty and one thing to remember is that I have set the threshold to 1 Byte because an empty file still takes some space of the system though it’s quite low. There are other ways as well for finding if the file is empty or not but none of them will find the file empty because it is occupying 1 Byte of space.
Conclusion
In bash scripting checking if a file exists and if it’s empty or not is a crucial aspect of shell scripting. In this article, we demonstrated how to check if a file exists and if it’s empty or not using a simple shell script. By setting a size threshold, you can customize the script to check if the file is empty based on your specific needs.