1

I want a unix command to check the directory is empty or not(need to exclude . and ..) ?

thanks in advance.

user2400564
  • 4,619
  • 7
  • 24
  • 27

4 Answers4

2

Try this, it is rather simple

[ "$(ls -A .)" ] && echo "Not Empty" || echo "Empty"

Found it on http://www.cyberciti.biz/faq/linux-unix-shell-check-if-directory-empty/

NaN
  • 7,441
  • 6
  • 32
  • 51
  • I'm not happy with 'ls' or any answer that puts all the entries in a pipe or variable when the directory may be (very) large. – 4dummies Jul 28 '19 at 16:32
1

I would use the following:

if [ `ls -A directory_to_test/ | wc -m` == "0" ]; then
    echo "empty"
else
    echo "not empty"
fi

ls -A will output the files in the directory, -A makes sure, that . and .. are excluded. wc -m will count the number of chars in the output, if that equals to the string 0, then the directory is empty. This will also count the "invisible" files.

Nidhoegger
  • 4,973
  • 4
  • 36
  • 81
0

See the "Determining if a directory is empty" section of this site:

is_empty () (
cd "$1"
set -- .[!.]* ; test -f "$1" && return 1
set -- ..?* ; test -f "$1" && return 1
set -- * ; test -f "$1" && return 1
return 0 )

This code uses the magic 3 globs which are needed to match all possible names except “.” and “..”, and also handles the cases where the glob matches a literal name identical to the glob string.

If you don’t care about preserving permissions, a simpler implementation is:

is_empty () { rmdir "$1" && mkdir "$1" ; }

Naturally both of the approaches have race conditions if the directory is writable by other users or if other processes may be modifying it. Thus, an approach like the latter but with a properly restrictive umask in effect may actually be preferable, as its result has the correct atomicity properties:

is_empty_2 () ( umask 077 ; rmdir "$1" && mkdir "$1" )

Also see the answers on this question.

Etan Reisner
  • 77,877
  • 8
  • 106
  • 148
-1

OP asked for a one-liner, so here's one that uses find without actually listing anything extra:

if [ -d some/dir -a -n "$( find some/dir -prune -empty 2>/dev/null )" ] ; then echo empty ; fi

or even

[ -d some/dir -a -n "$( find some/dir -prune -empty 2>/dev/null )" ] && echo empty

Find will produce either "some/dir" or else "", and will not descend into the directory's entries because -prune does the same thing as --maxdepth=0 with fewer characters.

If you relax the one-liner requirement, I'd put this in a Bash function to make it even more readable.

4dummies
  • 759
  • 2
  • 9
  • 22