Thursday, 19 July 2012

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
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

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"


No comments:

Post a Comment