Sunday, May 10, 2015

How check If File is Empty or Not using Bash Script

While working with bash shell programming, when you need to read some file content, It is good to test that given file is exits or not after that test if file is empty or not. This will safe your script from throwing errors. This article will help you to test if file exists or not and file is empty or not.

1. Check if File Empty or Not:-

This script will check if given file is empty or not. As per below example if /tmp/myfile.txt is an empty file then it will show output as “File empty”, else if file has some content it will show output as “File not empty”.
#!/bin/bash

if [ -s /tmp/myfile.txt ]
then
     echo "File not empty"
else
     echo "File empty"
fi

Above same if condition can be write in single line as below.
#!/bin/bash

[ -s /tmp/myfile.txt ] && echo "File not empty" || echo "File empty" 

2. Check if File Exists and Not Empty:

Below script will check if file exists and file is empty or not. As per below example if /tmp/myfile.txt does not exists, script will show output as “File not exists” and if file exists and is an empty file then it will show output as “File exists but empty”, else if file exists has some content in it will show output as “File exists and not empty”.
if [ -f /tmp/myfile.txt ]
then
    if [ -s /tmp/myfile.txt ]
    then
        echo "File exists and not empty"
    else
        echo "File exists but empty"
    fi
else
    echo "File not exists"
fi

3. Check if File Exists and Not Empty with Variable:

This is same as #2 except here file name is saved in a variable.

#!/bin/bash

FILENAME="/tmp/myfile.txt"

if [ -f ${FILENAME} ]
then
    if [ -s ${FILENAME} ]
    then
        echo "File exists and not empty"
    else
 echo "File exists but empty"
    fi
else
    echo "File not exists"
fi

No comments:

Post a Comment