Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if a file is empty in Bash?

I have a file called diff.txt. I Want to check whether it is empty.

I wrote a bash script something like below, but I couldn't get it work.

if [ -s diff.txt ]
then
        touch empty.txt
        rm full.txt
else
        touch full.txt
        rm emtpy.txt
fi
like image 565
Mich Avatar asked Apr 01 '12 13:04

Mich


People also ask

How do you know if a file is empty or not in bash?

Bash Script – Check If File is Empty or Not With the -s Option. However, one can pass the -s option as follows in script or shell prompt: touch /tmp/f1 echo "data" >/tmp/f2 ls -l /tmp/f{1,2} [ -s /tmp/f1 ] echo $? The non zero output indicate that file is empty.

Is empty in bash?

To find out if a bash variable is empty: Return true if a bash variable is unset or set to the empty string: if [ -z "$var" ]; Another option: [ -z "$var" ] && echo "Empty" Determine if a bash variable is empty: [[ ! -z "$var" ]] && echo "Not empty" || echo "Empty"


3 Answers

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.

like image 95
thb Avatar answered Oct 17 '22 02:10

thb


[ -s file.name ] || echo "file is empty"
like image 101
mickey white Avatar answered Oct 17 '22 01:10

mickey white


[ -s file ] # Checks if file has size greater than 0

[ -s diff.txt ] && echo "file has something" || echo "file is empty"

If needed, this checks all the *.txt files in the current directory; and reports all the empty file:

for file in *.txt; do if [ ! -s $file ]; then echo $file; fi; done
like image 72
Surya Avatar answered Oct 17 '22 02:10

Surya