check if a directory is empty in bash

April 19, 2008

programming

I had this small problem, how to you check if a directory is empty in the shell? Suppose I want to do

cmd po/*

this fails, if the po directory is empty, which in turn makes my compile barf, but that is another story. I needed something to would check the emptiness of the directory, and if it is not empty perform the command, otherwise it skip it.

The trick here is to remember that if a shell wildcard can not be expanded it will be left alone. So an unexpanded * will stay a *.

Thus

if [ po/* = "po/*" ]; then 
    echo empty
else
    echo loaded
fi

will check if a directory is empty. This can also be folded into one line

[ po/* = "po/*" ] || cmd po/*

UPDATE Jaap Akkerhuis reminded me that this (ofcourse) fails with hidden files as those are not expanded by *. This could be fixes by also checking for .*

Misc