How do I check if file is empty or not using bash or ksh shell script under UNIX / Linux / OS X / BSD operating systems?
You can use the find command as follows. The -s option to the test builtin check to see if FILE exists and has a size greater than zero. It returns true and false values to indicate that file is empty or has some data.
touch /tmp/file1 ls -l /tmp/file1 find /tmp -empty -name file1
Sample outputs:
/tmp/file1
Now create another file with some data in it:
echo "data" > /tmp/file2 ls -l /tmp/file2 find /tmp -empty -name file2
You should not see any output.
Shell -s option
However, use can pass -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 $?
Sample outputs:
1
The non zero output indicate that file is empty.
[ -s /tmp/f2 ] echo $?
Sample outputs:
0
The zero output indicate that file is not empty. So you can write a shell script as follows:
Shell Script To Check If File Is Empty OR Not
#!/bin/bash _file="$1" [ $# -eq 0 ] && { echo "Usage: $0 filename"; exit 1; } [ ! -f "$_file" ] && { echo "Error: $0 file not found."; exit 2; } if [ -s "$_file" ] then echo "$_file has some data." # do something as file has data else echo "$_file is empty." # do something as file is empty fi
Run it as follows:
chmod +x script.sh
./script.sh /etc/resolv.conf
Sample outputs:
/etc/resolv.conf has some data.
Run it on an empty file:
touch /tmp/test.txt
./script.sh /tmp/test.txt
Sample outputs:
test.txt is empty.
You should follow me on twitter here or grab rss feed to keep track of new changes.
Featured Articles:
- 30 Handy Bash Shell Aliases For Linux / Unix / Mac OS X
- Top 30 Nmap Command Examples For Sys/Network Admins
- 25 PHP Security Best Practices For Sys Admins
- 20 Linux System Monitoring Tools Every SysAdmin Should Know
- 20 Linux Server Hardening Security Tips
- Linux: 20 Iptables Examples For New SysAdmins
- Top 20 OpenSSH Server Best Security Practices
- Top 20 Nginx WebServer Best Security Practices
- 20 Examples: Make Sure Unix / Linux Configuration Files Are Free From Syntax Errors
- 15 Greatest Open Source Terminal Applications Of 2012

- My 10 UNIX Command Line Mistakes
- Top 10 Open Source Web-Based Project Management Software
- Top 5 Email Client For Linux, Mac OS X, and Windows Users
- The Novice Guide To Buying A Linux Laptop











{ 4 comments… read them below or add one }
Very helpful …
What if you there might be multiple files exist? ex:
file1, file2, file3
if [ -s "$file*" ] or if [-s file*]
do not work
any suggestions?
Thanks
Vivian
@Vivan
You need to edit the script:
#!/bin/bash [ $# -eq 0 ] && { echo "Usage: $0 file1 file2 fileN"; exit 1; } for _file in $@ do [ ! -f "$_file" ] && { echo "Error: $_file file not found."; continue; } if [ -s "$_file" ] then echo "$_file has some data." # do something as file has data else echo "$_file is empty." # do something as file is empty fi doneHow do send emails on the sample outputs in linux as a crontab