How do I check if a directory contains files? How do I find out if a directory contains files using bash shell under Linux or Unix like operating systems?
To test if folder is empty or not use the following methods.
Method # 1: Find command
The syntax is:
find /path/to/dir -maxdepth 0 -empty -exec echo {} is empty. \;
You can modify it as follows to work with shell if command:
#!/bin/bash dir=$1 [ $# -eq 0 ] && { echo "Usage: $0 directory"; exit 2; } [ ! -d "$dir" ] && { echo "$dir is not a directory."; exit 2; } if find "$dir" -maxdepth 0 -empty | read; then echo "$dir empty." else echo "$dir not empty." fi
Run the script as follows:
./script /etc
Sample outputs:
/etc not empty.
Create a directory / folder called /tmp/foo using mkdir command:
$ mkdir /tmp/foo
Run the script as follows:
./script /tmp/foo
Sample outputs:
/tmp/foo empty.
Method #2: Other commands
See our previous tutorial and comments for more info:
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












{ 5 comments… read them below or add one }
These’re hard ways! You can do it:
if [ `ls -A "$dir" | wc -l` -eq 0 ]; then echo “Empty!”; fi
In the find command you need to include the parameter -type d so that it searches only directories and not the files
if ! ls /path/to/dir/* 2> /dev/null; then echo Empty; fi
if ! ls /path/to/file/* 2> /dev/null; then
echo Empty;
fi
if ! ls /path/to/file/* 2> /dev/null; then echo Empty; fi