Centos 6/RHEL Test for Empty Folder with Bash Script

For a simple little shell script which can test whether any directory on your system is empty or not, do the following.

$ vi empty.sh

And copy/paste the following script

# !/bin/bash

[ $# -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;
 echo "$dir empty."
 echo "$dir not empty."

Save the file

See Vim Editor for vi commands 

chmod it to run as an exec

$ chmod +x empty.sh

Now test it out

$ ./empty.sh /proc              returns

/proc not empty.      

$ ./empty.sh /usr/bin           returns

$ /usr/bin not empty.           or a longer example

$ ./empty.sh /usr/share/fluxbox/styles     returns

$ /usr/share/fluxbox/styles not empty.

Especially suitable for Servers as well as Desktops, it saves you browsing all the way round your system to see empty directories.

Obviously it is limited to just checking if a directory is empty or not, but shell scripting wizards can probably modify it to work with the shell if command.

A single command to find files only would be similar to

$ find "/tmp" -type f -exec echo Found file {} \;    

Or for all contents

$ [ "$(ls -A /path/to/directory)" ] && echo "Not Empty" || echo "Empty"

The same with an example would be

$ [ "$(ls -A /usr/bin)" ] && echo "Not Empty" || echo "Empty"

Labels: , ,