Sunday, April 27, 2008

Check Whether a Directory is Empty or Not

1. Print file name from /tmp. If there is no output, directory is empty.

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

Found file /tmp/_.c
Found file /tmp/orbit-vivek/bonobo-activation-server-ior
...

2. The simplest and most effective way is to use ls with -A:

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

#!/bin/bash
FILE=""
DIR="/tmp"
# init
# look for empty dir
if [ "$(ls -A $DIR)" ]; then
echo "Take action $DIR is not Empty"
else
echo "$DIR is Empty"
fi
# rest of the logic

No comments: