[ALUG] How to check a directory is empty (probably in bash)?

Brett Parker iDunno at sommitrealweird.co.uk
Wed Feb 21 13:18:33 GMT 2007


On Wed, Feb 21, 2007 at 01:00:57PM -0000, Ted Harding wrote:
> On 21-Feb-07 Paul wrote:
> > On Wednesday 21 February 2007 11:42, Eur Ing Chris Green wrote:
> >> What's the simplest (and/or most concise) way to check for an empty
> >> directory?
> > 
> > if test -z `ls foo` ; then wibble ; fi
> > 
> >  Or
> > 
> > if [ -z `ls foo` ] ; then wibble ; fi
> > 
> > There's probably other ways....
> > 
> > Regards, Paul.
> 
> NB: `ls foo` will not detect filenames in foo that begin with "."
> 
> Hence my suggestion using "ls -la"; but this then outputs the
> "." for current, and ".." for parent directories, regardless
> of whether "foo" is empty (and also a first line which gives
> the "total"). Hence the test for "-eq 3".

Hence my use of ls -lAU, U is for unsorted - and thus is quicker than a
default ls, -A means "almost all files" and skips . and .., and as ls
gives a nice line containing "total" as the first line of output, it
seemed sensible to use that to find out if it contained anything or not
:)

Cheers,
-- 
Brett Parker



More information about the main mailing list