Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

Empty Directory problem

27 views
Skip to first unread message

newexpectuser

unread,
Oct 27, 2003, 1:55:02 PM10/27/03
to
I have a script running and I want to see if a directory is empty
(meaning not having any files).

I can't use the rmdir, because I don't want to remove the directory, I
just want to do the following:


if [ $DIR is empty ]
echo "The directory is empty" > $LOG/logfile.dat
exit
fi

Thank you

Lew Pitcher

unread,
Oct 27, 2003, 2:18:33 PM10/27/03
to

Perhaps you can make use of the fact that an empty directory will have a link
count of exactly 2, and you can test the output of ls -ld to check the number of
links the target has.

>
>Thank you

--
Lew Pitcher
IT Consultant, Enterprise Technology Solutions
Toronto Dominion Bank Financial Group

(Opinions expressed are my own, not my employers')

Stephane CHAZELAS

unread,
Oct 27, 2003, 2:37:17 PM10/27/03
to
2003/10/27, 10:55(-08), newexpectuser:

> I have a script running and I want to see if a directory is empty
> (meaning not having any files).
[...]

GNU find has a "-empty" predicate.

DIR=/some/dir

if `find "$DIR" -prune -empty -printf :` false; then
echo "$DIR is empty"
fi

Otherwise, you can use ls:

if r=`ls -a -- "$DIR" && echo .` \
&& [ "${#r}" -eq 8 ]; then
echo "$DIR is empty"
fi

--
Stéphane ["Stephane.Chazelas" at "free.fr"]

Barry Margolin

unread,
Oct 27, 2003, 2:39:33 PM10/27/03
to
In article <3f9d6f51...@news21.on.aibn.com>,

Lew Pitcher <Lew.P...@td.com> wrote:
>On 27 Oct 2003 10:55:02 -0800, anthon...@cs.com (newexpectuser) wrote:
>
>>I have a script running and I want to see if a directory is empty
>>(meaning not having any files).
>>
>>I can't use the rmdir, because I don't want to remove the directory, I
>>just want to do the following:
>>
>>
>>if [ $DIR is empty ]
>> echo "The directory is empty" > $LOG/logfile.dat
>> exit
>>fi
>
>Perhaps you can make use of the fact that an empty directory will have a link
>count of exactly 2, and you can test the output of ls -ld to check the number of
>links the target has.

A directory containing only files will also have a link count of 2. The
link count of a directory only increases due to subdirectories, not
ordinary files within it.

--
Barry Margolin, barry.m...@level3.com
Level(3), Woburn, MA
*** DON'T SEND TECHNICAL QUESTIONS DIRECTLY TO ME, post them to newsgroups.
Please DON'T copy followups to me -- I'll assume it wasn't posted to the group.

Stephane CHAZELAS

unread,
Oct 27, 2003, 2:41:18 PM10/27/03
to
2003/10/27, 19:18(+00), Lew Pitcher:
[...]

> Perhaps you can make use of the fact that an empty directory will have a link
> count of exactly 2

Yes, as well as non-empty directories that don't have
sub-directories.

Heiner Steven

unread,
Oct 27, 2003, 3:00:32 PM10/27/03
to
newexpectuser wrote:

> I have a script running and I want to see if a directory is empty
> (meaning not having any files).

[...]

Why do you need to know if the directory is empty? If you
e.g. want to run a command there only when there are files,
you could do something like the following:

for file in *
do
[ -f "$file" ] || continue
# do something useful with "$file"
done

If you still need to know if a directory is empty,
you can also use

if [ X`ls -a -- "$dir" | wc -l` -eq X2 ]
then
echo "directory is empty: $dir"
fi

Heiner
--
___ _
/ __| |_ _____ _____ _ _ Heiner STEVEN <heiner...@nexgo.de>
\__ \ _/ -_) V / -_) ' \ Shell Script Programmers: visit
|___/\__\___|\_/\___|_||_| http://www.shelldorado.com/

Lew Pitcher

unread,
Oct 27, 2003, 2:54:24 PM10/27/03
to
On Mon, 27 Oct 2003 19:39:33 GMT, Barry Margolin <barry.m...@level3.com>
wrote:

>In article <3f9d6f51...@news21.on.aibn.com>,
>Lew Pitcher <Lew.P...@td.com> wrote:
>>On 27 Oct 2003 10:55:02 -0800, anthon...@cs.com (newexpectuser) wrote:
>>
>>>I have a script running and I want to see if a directory is empty
>>>(meaning not having any files).
>>>
>>>I can't use the rmdir, because I don't want to remove the directory, I
>>>just want to do the following:
>>>
>>>
>>>if [ $DIR is empty ]
>>> echo "The directory is empty" > $LOG/logfile.dat
>>> exit
>>>fi
>>
>>Perhaps you can make use of the fact that an empty directory will have a link
>>count of exactly 2, and you can test the output of ls -ld to check the number of
>>links the target has.
>
>A directory containing only files will also have a link count of 2. The
>link count of a directory only increases due to subdirectories, not
>ordinary files within it.

Good point.

That'll teach me to answer of the top of my head ;-)

Thanks

William Park

unread,
Oct 27, 2003, 3:10:18 PM10/27/03
to

Look at output of
ls -a
du -s

--
William Park, Open Geometry Consulting, <openge...@yahoo.ca>
Linux solution for data management and processing.

Dan Mercer

unread,
Oct 27, 2003, 4:08:51 PM10/27/03
to

"Lew Pitcher" <Lew.P...@td.com> wrote in message news:3f9d6f51...@news21.on.aibn.com...

: On 27 Oct 2003 10:55:02 -0800, anthon...@cs.com (newexpectuser) wrote:
:
: >I have a script running and I want to see if a directory is empty
: >(meaning not having any files).
: >
: >I can't use the rmdir, because I don't want to remove the directory, I
: >just want to do the following:
: >
: >
: >if [ $DIR is empty ]
: > echo "The directory is empty" > $LOG/logfile.dat
: > exit
: >fi
:
: Perhaps you can make use of the fact that an empty directory will have a link
: count of exactly 2, and you can test the output of ls -ld to check the number of
: links the target has.

As long as none of the files is a directory, the link count will be 2.

Try:

for i in $DIR/* $DIR/.[!.]*
do
[ -e $i ] || continue
echo "$DIR is not empty"
# whatever other control structures are necessary
break
done

Dan Mercer
:
: >
: >Thank you

Scott McMillan

unread,
Oct 27, 2003, 4:09:41 PM10/27/03
to
On 27 Oct 2003 10:55:02 -0800, anthon...@cs.com (newexpectuser)
wrote:

>I have a script running and I want to see if a directory is empty

I wonder if this would work for you (filenames starting with a period
would be found as well, subdirectories not checked):

cd /<yourdirectoryname>
if [ -z `find ./ -type f -print` ]; then
echo "Directory is empty"
else
echo "Directory contains files"
fi

If you are not concerned with whether or not 'hidden' (filenames
beginning with a period) are in the directory, I think you could use
something like:

cd /yourdirectoryname
ls -l | grep "total 0" >/dev/null
if [ $? = 0 ]; then
echo "Directory is empty"
else
echo "Directory contains files"
fi

However, subdirectories within <yourdirectoryname> would trigger
"Directory contains files".


Scott McMillan

jmdevil

unread,
Oct 27, 2003, 3:32:17 PM10/27/03
to

#!/usr/bin/ksh

n=$(ls -Ac $DIR | wc -w)

if [ $n -eq 0 ]

then

echo DIRECTORY IS EMPTY

fi

-- JM


--
Posted via http://dbforums.com

laura fairhead

unread,
Oct 27, 2003, 3:33:52 PM10/27/03
to
In article <Vvenb.241$lK3...@news.level3.com>, Barry Margolin wrote:
>In article <3f9d6f51...@news21.on.aibn.com>,
>Lew Pitcher <Lew.P...@td.com> wrote:
>>On 27 Oct 2003 10:55:02 -0800, anthon...@cs.com (newexpectuser) wrote:
>>
>>>I have a script running and I want to see if a directory is empty
>>>(meaning not having any files).
>>>
>>>I can't use the rmdir, because I don't want to remove the directory, I
>>>just want to do the following:
>>>
>>>
>>>if [ $DIR is empty ]
>>> echo "The directory is empty" > $LOG/logfile.dat
>>> exit
>>>fi
>>
>>Perhaps you can make use of the fact that an empty directory will have a link
>>count of exactly 2, and you can test the output of ls -ld to check the number of
>>links the target has.
>
>A directory containing only files will also have a link count of 2. The
>link count of a directory only increases due to subdirectories, not
>ordinary files within it.

Is it even guarenteed that every directory has to have a '.' and a '..'
file ? Certainly one would expect the '.' to be mandatory for obvious
reasons however is it true that there has to be an entry for '..' always?

I was looking briefly through POSIX and it doesn't seem to mandate it.


byefornow
laura

>
>--
>Barry Margolin, barry.m...@level3.com
>Level(3), Woburn, MA
>*** DON'T SEND TECHNICAL QUESTIONS DIRECTLY TO ME, post them to newsgroups.
>Please DON'T copy followups to me -- I'll assume it wasn't posted to the group.


--
echo alru_aa...@ittnreen.tocm |sed 's/\(.\)\(.\)/\2\1/g'

laura fairhead

unread,
Oct 27, 2003, 4:15:29 PM10/27/03
to
In article <slrnbpqsvd.4f.s...@spam.is.invalid>,
Stephane CHAZELAS wrote:

>2003/10/27, 10:55(-08), newexpectuser:
>> I have a script running and I want to see if a directory is empty
>> (meaning not having any files).
>[...]
>
>GNU find has a "-empty" predicate.
>
>DIR=/some/dir
>
>if `find "$DIR" -prune -empty -printf :` false; then
> echo "$DIR is empty"
>fi
>
>Otherwise, you can use ls:
>
>if r=`ls -a -- "$DIR" && echo .` \
> && [ "${#r}" -eq 8 ]; then
> echo "$DIR is empty"
>fi

Hi Stephane,

This doesn't work here, where ${#r} is 6 on an empty directory.

Also, ${#r} isn't plain bourne shell (well okay it is POSIX).

Or,... there was a thread about this a while ago to do it without
a loop (although there shouldn't be much difference since a loop
will only go around 4 times maximum). To use that code for any
directory just 'cd' to the directory first (in a subshell of course)

From: Matt <matt...@hotmail.com>
Newsgroups: comp.unix.shell
Subject: How to test for just one file
Date: Sun, 02 Mar 2003 23:14:12 -0500
Message-ID: <matt7846-9E746C...@corp.supernews.com>

Or on google;

http://groups.google.com/groups?hl=en&lr=&ie=UTF-\
8&frame=right&th=1b4544d7fac6a84b&seekm=slrnb68n\
th.4j.stephane_chazelas%40pcchazelas.free.fr#link7

>
>--
>Stéphane ["Stephane.Chazelas" at "free.fr"]


byefornow
laura

Ben

unread,
Oct 27, 2003, 4:26:05 PM10/27/03
to
laura fairhead wrote:
> Is it even guarenteed that every directory has to have a '.' and a '..'
> file ? Certainly one would expect the '.' to be mandatory for obvious
> reasons however is it true that there has to be an entry for '..' always?
>
> I was looking briefly through POSIX and it doesn't seem to mandate it.

Sounds strange that a system wouldn't have ".." - what would you do to
go down a directory level? Either the sytem would use a non-standard way
or you would need to provide an absolute path?

regards,
Ben

--
My contact info: Username:ng4.replies.benaltw Domain:xoxy.net

Cheap long distance calling using Onesuite (http://www.onesuite.com).
2.5 cents/min anywhere in the U.S., to Canada or the U.K.
Use promotional code 038664643 for 20 free minutes.

laura fairhead

unread,
Oct 27, 2003, 4:38:31 PM10/27/03
to
In article <DPfnb.79564$pg7....@twister.rdc-kc.rr.com>, Dan Mercer wrote:
>
>"Lew Pitcher" <Lew.P...@td.com> wrote in message news:3f9d6f51...@news21.on.aibn.com...
>: On 27 Oct 2003 10:55:02 -0800, anthon...@cs.com (newexpectuser) wrote:
>:
>: >I have a script running and I want to see if a directory is empty
>: >(meaning not having any files).
>: >
>: >I can't use the rmdir, because I don't want to remove the directory, I
>: >just want to do the following:
>: >
>: >
>: >if [ $DIR is empty ]
>: > echo "The directory is empty" > $LOG/logfile.dat
>: > exit
>: >fi
>:
>: Perhaps you can make use of the fact that an empty directory will have a link
>: count of exactly 2, and you can test the output of ls -ld to check the number of
>: links the target has.
>
>As long as none of the files is a directory, the link count will be 2.

Does this always have to be true on every system though? eg; Couldn't
a root with no subdirectories have a link count of 1 ?

>
>Try:
>
> for i in $DIR/* $DIR/.[!.]*
> do
> [ -e $i ] || continue
> echo "$DIR is not empty"
> # whatever other control structures are necessary
> break
> done

No. A directory with one file called "..abc" for example would break
that, I would add another pattern;

for i in "$DIR"/* "$DIR"/..?* "$DIR"/.[!.]*


do
[ -e $i ] || continue
echo "$DIR is not empty"

break
done


seeyafrom
laura

>
>Dan Mercer
>:
>: >
>: >Thank you
>:
>: --
>: Lew Pitcher
>: IT Consultant, Enterprise Technology Solutions
>: Toronto Dominion Bank Financial Group
>:
>: (Opinions expressed are my own, not my employers')
>
>

j...@invalid.address

unread,
Oct 27, 2003, 4:46:30 PM10/27/03
to
anthon...@cs.com (newexpectuser) writes:

> I have a script running and I want to see if a directory is empty
> (meaning not having any files).

One possibility:

if [ `ls -a tmp | wc -l` -ne 2 ];then echo not empty;fi

Joe

rakesh sharma

unread,
Oct 27, 2003, 5:38:24 PM10/27/03
to
anthon...@cs.com (newexpectuser) wrote in message news:<f0bb0f39.03102...@posting.google.com>...

cd "$DIR"
[ -n "`ls -1A | head -1`" ] || echo "The directory '$DIR' is empty"

(untested)

Stephane CHAZELAS

unread,
Oct 27, 2003, 5:24:31 PM10/27/03
to
2003/10/27, 21:15(+00), laura fairhead:
[...]

>>if r=`ls -a -- "$DIR" && echo .` \
>> && [ "${#r}" -eq 8 ]; then
>> echo "$DIR is empty"
>>fi
>
> This doesn't work here, where ${#r} is 6 on an empty directory.
[...]

Yes, just as everywhere else. I'll just have to learn how to
count on my fingers ".\n..\n." are 6 characters (note the "echo
." or it would fail with a file named ^J). You can also add the
"-f" flag to "ls" to prevent the unnecessary sorting.

if r=$(ls -af -- "$DIR" && echo .) \
&& [ "${#r}" -le 6 ]; then


echo "$DIR is empty"
fi

But I agree, it assumes "." and ".." are present. They may not (like
with a smb or NFS remote FS from a MSDOS system?)

> Or,... there was a thread about this a while ago to do it without
> a loop (although there shouldn't be much difference since a loop
> will only go around 4 times maximum). To use that code for any
> directory just 'cd' to the directory first (in a subshell of course)

I remember well this thread. But in the:

set x * [*] .[!.]* '.[!.]'[*] .[.]?*
IFS=" "; case $* in
"x * [*] .[!.]* .[!.][*] .[.]?*") # no files
;;
*) # files found
;;
esac

Or:

set x * [*] .[!.] .??* '.??'[*]
IFS=" "; case $* in
"x * [*] .[!.] .??* .??[*]") # no files
;;
*) # files found
;;
esac

You first need to cd into the directory, and if you're already
there, but don't have the right to list the directory, you won't
get an error message.

If you don't cd to the directory, you first need to check if it
exists.

Stephane CHAZELAS

unread,
Oct 27, 2003, 5:37:56 PM10/27/03
to
2003/10/27, 21:08(+00), Dan Mercer:
[...]

> for i in $DIR/* $DIR/.[!.]*

You're missing ..?* files.

> do
> [ -e $i ] || continue

"[ -e " is not in every shell. In shells/tests that support it,
it stats the file. A directory that contains only unstatable
files would be claimed empty.

$ mkdir /tmp/tmp
$ touch /tmp/tmp/foo
$ chmod 444 /tmp/tmp
$ ls -a /tmp/tmp
. .. foo
$ [ -e /tmp/tmp/foo ] || echo NO
NO
$

laura fairhead

unread,
Oct 27, 2003, 6:21:39 PM10/27/03
to
In article <ed24e4cf.03102...@posting.google.com>,

I wouldn't rely on the -A option being present on a given system
but more to the point is that this breaks if the first filename in
the alphabetical sorted output has NEWLINE as its first character,

$ mkdir tmp
$ cd tmp
$ : >'
'
$ [ -n "`ls -A |head -1`" ] ||echo empty
empty
$

wc could fix that;

[ `ls -A |wc -l` -eq 0 ] && echo empty


byefrom
laura

>
>(untested)

John

unread,
Oct 27, 2003, 7:17:17 PM10/27/03
to
anthon...@cs.com (newexpectuser) wrote:

> ... I just want to do the following:


>
>
> if [ $DIR is empty ]
> echo "The directory is empty" > $LOG/logfile.dat
> exit
> fi
>

what shell? what OS? in ksh on most unix's, if you do "ls /mydir"
and "/mydir" is empty you get a null return ... if you do "ls -l
/mydir" and it is empty, you get the message "total 0" which indicates
an empty dir ... so your test could look like this:

if [ -d $DIR ] # test to see if $DIR exists
then
if [ `ls -l $DIR` == "total 0" ]
then echo "the directory is empty" >/yourlogfile
else echo "the dir is not empty"
fi
else echo "$DIR does not exist"
fi

Don't forget to read the manpage for ls to find the relevant forms for
your shell & OS.

regards,
John

Walt R

unread,
Oct 28, 2003, 1:08:04 AM10/28/03
to
laura_f...@INVALID.com (laura fairhead) wrote in message news:<slrnbpra3v.ue....@bell486.bittersweet.org>...

lsl is an alias for ls -l. If you do an ls -l of an empty dir, there
is one line of output. if there are four files, there are five lines
of output.

[wmr@localhost wmr]$ lsl linuxdoc
total 296
drwxrwxr-x 2 wmr wmr 4096 Jun 1 14:38 abs-guide
drwxrwxr-x 2 wmr wmr 4096 Jun 1 14:43 bashguide
drwxrwxr-x 2 wmr wmr 4096 Jun 1 17:45
Pocket-Linux-Guide
-rw-rw-r-- 1 wmr wmr 283932 Aug 4 21:16 smithch10.pdf
[wmr@localhost wmr]$ lsl empty # empty is empty
total 0
[wmr@localhost wmr]$ lsl empty |wc -l
1
[wmr@localhost wmr]$

Walt R.

Stephane CHAZELAS

unread,
Oct 27, 2003, 5:46:33 PM10/27/03
to
2003/10/27, 14:38(-08), rakesh sharma:
[...]

> cd "$DIR"
> [ -n "`ls -1A | head -1`" ] || echo "The directory '$DIR' is empty"

ls -A is not much portable (not POSIX).

Stephane CHAZELAS

unread,
Oct 28, 2003, 2:31:14 AM10/28/03
to
2003/10/27, 16:17(-08), John:
[...]

> if [ -d $DIR ] # test to see if $DIR exists
"$DIR"

> then
> if [ `ls -l $DIR` == "total 0" ]
"total 0" = "`ls -l \"$DIR\" | head -1`"

> then echo "the directory is empty" >/yourlogfile

[...]
then echo "the directory is empty or is not executable" >/yourlogfile

Geoff Clare

unread,
Oct 28, 2003, 9:23:25 AM10/28/03
to
Ben <ab...@efg.com> writes:

>Sounds strange that a system wouldn't have ".." - what would you do to
>go down a directory level?

Assuming you mean "up" not "down", you would use "cd .." (or
chdir("..") in a C program). POSIX requires this to work regardless
of whether a directory entry for ".." exists. (It specifies the
meaning of ".." in pathnames. Likewise for ".").

--
Geoff Clare <nos...@gclare.org.uk>

Geoff Clare

unread,
Oct 28, 2003, 9:17:47 AM10/28/03
to
laura_f...@INVALID.com (laura fairhead) writes:

>Is it even guarenteed that every directory has to have a '.' and a '..'
>file ? Certainly one would expect the '.' to be mandatory for obvious
>reasons however is it true that there has to be an entry for '..' always?

>I was looking briefly through POSIX and it doesn't seem to mandate it.

POSIX doesn't mandate entries for "." and "..". I believe the only
restriction it has is that it doesn't allow one to exist without the
other. See the description of readdir():

"If entries for dot or dot-dot exist, one entry shall be returned
for dot and one entry shall be returned for dot-dot; otherwise,
they shall not be returned."

--
Geoff Clare <nos...@gclare.org.uk>

Ben

unread,
Oct 28, 2003, 9:45:58 AM10/28/03
to
Geoff Clare wrote:
> Ben <ab...@efg.com> writes:
>>Sounds strange that a system wouldn't have ".." - what would you do to
>>go down a directory level?
>
>
> Assuming you mean "up" not "down", you would use "cd .." (or

Hey, I'm from Australia...

> chdir("..") in a C program). POSIX requires this to work regardless
> of whether a directory entry for ".." exists. (It specifies the
> meaning of ".." in pathnames. Likewise for ".").

Aaah. That's interesting.

Ben

unread,
Oct 28, 2003, 10:51:51 AM10/28/03
to
Geoff Clare wrote:
> Assuming you mean "up" not "down", you would use "cd .." (or

I look at the directory structure as a tree starting off at root. Which
means you go up the tree to get to a directory and down to go back to
root. On the other hand, I have never given it enough thought to know if
I am consistent about that. On the hand, I don't think that there is an
official direction.

Barry Margolin

unread,
Oct 28, 2003, 10:53:59 AM10/28/03
to
In article <bnm3an$13a6ca$1...@ID-121117.news.uni-berlin.de>,

Ben <ab...@efg.com> wrote:
>Geoff Clare wrote:
>> Assuming you mean "up" not "down", you would use "cd .." (or
>
>I look at the directory structure as a tree starting off at root. Which
>means you go up the tree to get to a directory and down to go back to
>root. On the other hand, I have never given it enough thought to know if
>I am consistent about that. On the hand, I don't think that there is an
>official direction.

In computer science, trees are virtually always considered inverted, with
the root at the top and recursion going down.

Ben

unread,
Oct 28, 2003, 11:25:56 AM10/28/03
to
Barry Margolin wrote:
> In article <bnm3an$13a6ca$1...@ID-121117.news.uni-berlin.de>,
> Ben <ab...@efg.com> wrote:
>
>>Geoff Clare wrote:
>>
>>>Assuming you mean "up" not "down", you would use "cd .." (or
>>
>>I look at the directory structure as a tree starting off at root. Which
>>means you go up the tree to get to a directory and down to go back to
>>root. On the other hand, I have never given it enough thought to know if
>>I am consistent about that. On the hand, I don't think that there is an
>>official direction.
>
>
> In computer science, trees are virtually always considered inverted, with
> the root at the top and recursion going down.

You're right. I stand corrected.

Stephane CHAZELAS

unread,
Oct 28, 2003, 11:39:01 AM10/28/03
to
2003/10/28, 10:51(-05), Ben:

> Geoff Clare wrote:
>> Assuming you mean "up" not "down", you would use "cd .." (or
>
> I look at the directory structure as a tree starting off at root. Which
> means you go up the tree to get to a directory and down to go back to
> root. On the other hand, I have never given it enough thought to know if
> I am consistent about that. On the hand, I don't think that there is an
> official direction.

Note that FTP has a CD*UP* command which doesn't *descend* into
subdirectories.

RFC 959:

RFC> CHANGE TO PARENT DIRECTORY (CDUP)
RFC>
RFC> This command is a special case of CWD, and is included to
RFC> simplify the implementation of programs for transferring
RFC> directory trees between operating systems having different
RFC> syntaxes for naming the parent directory.

0 new messages