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.
Easiest way for checking file is empty or not:
if [ -s /path-to-file/filename.txt ]
then
echo "File is not empty"
else
echo "File is empty"
fi
You can also write it on single line:
[ -s /path-to-file/filename.txt ] && echo "File is not empty" || echo "File is empty"
I came here looking for how to delete empty __init__.py
files as they are implicit in Python 3.3+ and ended up using:
find -depth '(' -type f -name __init__.py ')' -print0 |
while IFS= read -d '' -r file; do if [[ ! -s $file ]]; then rm $file; fi; done
Also (at least in zsh) using $path as the variable also breaks your $PATH env and so it'll break your open shell. Anyway, thought I'd share!
Misspellings are irritating, aren't they? Check your spelling of empty
, but then also try this:
#!/bin/bash -e
if [ -s diff.txt ]
then
rm -f empty.txt
touch full.txt
else
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.
[[ -f filename && ! -s filename ]] && echo "filename exists and is empty"
To check if file is empty or has only white spaces, you can use grep:
if [[ -z $(grep '[^[:space:]]' $filename) ]] ; then
echo "Empty file"
...
fi
[[ -s file ]] --> Checks if file has size greater than 0
if [[ -s diff.txt ]]; then echo "file has something"; else echo "file is empty"; fi
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