Bash Script to Check If File is Empty or Not

Channel: Linux
Abstract: /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

While working with bash shell programming, when you need to read some file content. It is good to test that the given file exits or is not empty. This will safe your script from throwing errors. This article will help you to test if the file exists or not and the 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" fi12345678#!/bin/bash if [ -s /tmp/myfile.txt ]then     echo "File not empty"else     echo "File empty"fi

For the best practice, you can also write the above script in a single line as follows.

#!/bin/bash [ -s /tmp/myfile.txt ] && echo "File not empty" || echo "File empty"123#!/bin/bash [ -s /tmp/myfile.txt ] && echo "File not empty" || echo "File empty"

2. Check if File Exists and Not Empty

The below script will check if the file exists and the file is empty or not. As per below example if /tmp/myfile.txt does not exist, 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" fi1234567891011if [ -f /tmp/myfile.txt ]then    if [ -s /tmp/myfile.txt ]    then        echo "File exists and not empty"    else        echo "File exists but empty"    fielse    echo "File not exists"fi

3. Check if File Exists and Not Empty with Variable

This is the 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" fi123456789101112131415#!/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"    fielse    echo "File not exists"fi

Ref From: tecadmin

Related articles