How to Check If a File Is Empty in Bash

How to check if a file is empty in Bash?

Misspellings are irritating, aren't they? Check your spelling of empty, but then also try this:

#!/bin/bash -e

if [ -s diff.txt ]; then
# The file is not-empty.
rm -f empty.txt
touch full.txt
else
# The file is empty.
rm -f full.txt
touch empty.txt
fi

I like shell scripting a lot, but one disadvantage of it is that the shell cannot help you when you misspell, whereas a compiler like your C++ compiler can help you.

Notice incidentally that I have swapped the roles of empty.txt and full.txt, as @Matthias suggests.

Bash- How to check if file is empty in a loop

Why not just use a while?

while ! [ -s diff.txt ]; do
echo "file is empty - keep checking it "
sleep 1 # throttle the check
done
echo "file is not empty "
cat diff.txt

The loop will run as long as ! [ -s diff.txt ] is true. If you prefer, you can use until instead of while and remove the negation (!).

Checking if files are empty or not through Linux command line

Job for find (GNU find precisely), assuming the extension to match is .txt, and directory to check is /directory:

find /directory -maxdepth 1 -type f -name '*.txt' -not -empty

Recursively:

find /directory -type f -name '*.txt' -not -empty

Slow shell-way, using for to iterate over the files, and test ([) to check the conditions:

for f in /directory/*.txt; do [ -f "$f" ] && [ -s "$f" ] && echo "$f"; done

Recursively, with bash's globstar:

shopt -s globstar
for f in /directory/**/*.txt; do [ -f "$f" ] && [ -s "$f" ] && echo "$f"; done

Check file empty or not

You may use this awk for this:

awk 'NF {exit 1}' file && echo "empty" || echo "not empty"

Condition NF will be true only if there is non-whitespace character in the file.

Always gives false even though file exists and is not empty

It is enough to check for -s, because it says:

FILE exists and has a size greater than zero

http://unixhelp.ed.ac.uk/CGI/man-cgi?test

also your output is switched, so it outputs does not exists when a file exists, because -s will give TRUE if file exists AND has a size > 0.

So correctly you should use:

echo " enter file name "
read file
if [ -s "$file" ]
then
echo " file exists and is not empty "
else
echo " file does not exist, or is empty "
fi

This will give you the expected output.

Also it should be

read file

instead of

read $file

If you want further informations, I recommand reading man test and man read

check if file is empty or not

The test(1) program has a -s switch:

-s FILE
FILE exists and has a size greater than zero

How to check if a line from a file is empty with bash

You can use the test:

[ -z "$line" ]

From the bash man page:

-z string

True if the length of string is zero.



Related Topics



Leave a reply



Submit