It is currently Fri, 18 Apr 2014 20:42:43 GMT



 
Author Message
 How to determine if directory is empty using /bin/sh
How is the best way (fastest, I guess) to tell if a directory is empty
(i.e., only contains "." and "..") in a /bin/sh script?
--
J. Porter Clark    j...@avdms8.msfc.nasa.gov or j...@eb23.msfc.nasa.gov
NASA/MSFC Communications Systems Branch


 Sat, 25 Jun 1994 09:27:56 GMT   
 How to determine if directory is empty using /bin/sh
My guess follows.  This works, but is it fastest? You tell me.

#!/bin/sh
dir=foodir
count=`ls -a $dir | wc -l`
if [ $count -eq 2 ]
then
        echo "Directory $dir is empty."
else
        echo "Directory $dir is not empty."
fi

Jim Rogers
Hewlett-Packard Company



 Sat, 25 Jun 1994 23:44:54 GMT   
 How to determine if directory is empty using /bin/sh
I initially wrote a script similar to this one:

(This script is ss1 in my tests)
#!/bin/sh
if [ `ls -a $1 | wc -l` -eq 2 ]
then
  echo Directory $1 is empty
else
  echo Directory $1 is not empty
fi

My second solution is this one:

(This script is ss2 in the tests)
#!/bin/sh
if rmdir $1 2>/dev/null
then
  mkdir $1
  echo Directory $1 is empty
else
  echo Directory $1 is not empty
fi

I tested these by running each one 20 times, and running /bin/time.

If foo contains 250 files

/bin/time ss1 foo >/dev/null
       15.3 real         0.9 user         5.7 sys  
/bin/time ss2 foo >/dev/null
        4.8 real         0.5 user         3.8 sys  

If foo contains 1 file

/bin/time ss1 foo >/dev/null
       10.4 real         0.8 user         5.7 sys  
/bin/time ss2 foo >/dev/null
        4.0 real         0.5 user         3.2 sys  

If foo is empty empty

/bin/time ss1 foo >/dev/null
       11.5 real         0.8 user         5.7 sys  
/bin/time ss2 foo > /dev/null
       11.4 real         0.7 user         5.7 sys  

So, it seems that ss2 is marginally better in the worst case (when the



 Sun, 26 Jun 1994 04:59:45 GMT   
 How to determine if directory is empty using /bin/sh
A not quite 100% correct solution is:

#!/bin/sh
tmp1=`echo *`
tmp2=`echo .??*`
if [ "$tmp1" = '*'  -a  "$tmp2" = '.??*' ]; then
        # directory is empty
else
        # directory is not empty
fi

Now, if there are files named '*' and '.??*' in your directory (easy enough to
do, just type "touch '*'"), the above test will fail.  But if you name  
files like that, you have more problems than I can solve over USENET :-)

--
Jim
barr...@ial4.jsc.nasa.gov
Disclaimers and all that ...



 Sun, 26 Jun 1994 06:13:08 GMT   
 How to determine if directory is empty using /bin/sh

  Either of these shell programs will work.  The first is wordier, but
actually runs a wee bit faster:

    ls -a ${1?} |
        while read entry
        do
            case $entry in
                .|..)
                    continue;;
                *)
                    exit 1;;
            esac
        done

    exit 0

i.e., exit upon encountering an entry in the named directory other than
`.' or `..'.  The second is a one-liner:

    [ `ls -a ${1?} | wc -l` = 2 ]

i.e., test that the directory contains exactly two entries.

--
Roger Rohrbach                                  sun!wrs!roger    ro...@wrs.com
- Eddie sez: ----------------------------------------------- (c) 1986, 1992 -.
|   {o >o                                                                     |
|    \ ^) "I was drowning my sorrows, but my sorrows they learned to swim.    |



 Sat, 25 Jun 1994 12:04:38 GMT   
 How to determine if directory is empty using /bin/sh
Message-ID: <28790008@hplsdv7.hp.com>(Jim Rogers)

Let's call your scrip as jim.sh, and mine (shown below) as suley.sh

#! /bin/sh
dir=.
if ls -l $dir | grep 'total 0'
then
        echo "Directory $dir is empty."
else
        echo "Directory $dir is not empty."
fi

Runnung throug 'time' by setting dir=. in both scripts, gives the
following results

$ time suley.sh
Directory . is not empty.
        0.5 real         0.0 user         0.0 sys

$ time jim.sh
Directory . is not empty.
        0.4 real         0.0 user         0.2 sys

Detailed output can be observed by Csh's time:

% time suley.sh
Directory . is not empty.
0.020u 0.090s 0:00.65 16.9% 0+112k 0+0io 0pf+0w

% time jim.sh
Directory . is not empty.
0.040u 0.080s 0:00.24 50.0% 0+119k 0+0io 0pf+0w

Regards S.Kondakci

------------------------------------------------------------------------
----
Suleyman Kondakci                       Gaustadalleen 23,
University Computing Centre             P.O.Box 1059 Blindern
University of Oslo, Norway              N-0316 Oslo, Norway    

Tel.office: +47 2 453509 (direct)
Fax:        +47 2 453730        

E-mail: su...@usit.uio.no, Suleyman.Konda...@usit.uio.no
TextEncodedORaddress:
C=no/PRMD=uninett/O=uio/OU=usit/S=kondakci/G=Suleyman
------------------------------------------------------------------------
----



 Sun, 26 Jun 1994 22:44:16 GMT   
 How to determine if directory is empty using /bin/sh
\A not quite 100% correct solution is:
\
\#!/bin/sh
\tmp1=`echo *`
\tmp2=`echo .??*`
\if [ "$tmp1" = '*'  -a  "$tmp2" = '.??*' ]; then
\        # directory is empty
\else
\        # directory is not empty
\fi
\
\Now, if there are files named '*' and '.??*' in your directory (easy enough to
\do, just type "touch '*'"), the above test will fail.  But if you name  
\files like that, you have more problems than I can solve over USENET :-)

The following script deals with funny names and uses only
built-in commands!

------------------------------cut here------------------------------
#!/bin/sh
# test if a directory is empty

cd "${1-.}"

set .* ? *

case $#$3$4 in
4\?\*)
        exit 0
esac

exit 1



 Mon, 27 Jun 1994 03:07:55 GMT   
 How to determine if directory is empty using /bin/sh
|Message-ID: <28790...@hplsdv7.hp.com>(Jim Rogers)
|
|>My guess follows.  This works, but is it fastest? You tell me.
|
|>#!/bin/sh
|>dir=foodir
|>count=`ls -a $dir | wc -l`
|>if [ $count -eq 2 ]
|>then
|>   echo "Directory $dir is empty."
|>else
|>   echo "Directory $dir is not empty."
|>fi
|
|>Jim Rogers
|>Hewlett-Packard Company
|
|Let's call your scrip as jim.sh, and mine (shown below) as suley.sh
|
|#! /bin/sh
|dir=.
|if ls -l $dir | grep 'total 0'
|then
|       echo "Directory $dir is empty."
|else
|       echo "Directory $dir is not empty."
|fi
|

[stuff showing suley.sh runs faster deleted]

Nope.  Just another program that produces the wrong answer faster
than the right answer.  See if it works when you:
    mkdir junk
    cd junk
    echo noise > 'total 0'
    suley.sh    # presuming that suley.sh is in your path

However, there's a chance.  I'm not sure how portable, but
    if ls -l $dir | fgrep -x 'total 0'
would work on my Sun.  (fgrep -x requires _exact_ match on line.)

The other problem may be: just how portable is that "total 0" response
from ls -l???

|Regards S.Kondakci

Regards, Stan Ryckman  s...@alden.UUCP



 Tue, 28 Jun 1994 02:12:27 GMT   
 How to determine if directory is empty using /bin/sh
This should do the trick in sh or ksh:

for i
do cd $i
 if [ ". .. * ?" = "`echo .* * ?`" ]
 then echo This directory is deserted.
 else echo We\'ve discovered files!
 fi
done

If there is a file named '.*' then `echo .*` will return ". .* .." instead
of ". .."; if there is a file named '*' then `echo * ?` will produce "* *"
instead of "* ?"; if there is a file named '?' then `echo * ?` will generate
"? ?" instead of "* ?".  It does assume r and x permission on the directory
you want to test, but I suppose that without r and x permission there really
is no value to knowing whether it is empty anyway.

It looks fairly foolproof.  I haven't been able to break it in sh or ksh.

adr...@milton.u.washington.edu (Adrian Mariano) suggested in
<1992Jan7.205945.1...@milton.u.washington.edu>:

| #!/bin/sh
| if rmdir $1 2>/dev/null
| then
|   mkdir $1
|   echo Directory $1 is empty
| else
|   echo Directory $1 is not empty
| fi

That one runs into problems if you don't have write permission on the
parent of $1; the directory may be empty but rmdir will still return a
bad exit status.

David W. Tamkin  Box 7002  Des Plaines, Illinois  60018-7002  +1 708 518 6769
datt...@gagme.chi.il.us  CIS: 73720,1570  MCI Mail: 426-1818  +1 312 693 0580



 Mon, 27 Jun 1994 02:48:15 GMT   
 How to determine if directory is empty using /bin/sh
Is a directory empty?   SUMMERY SO FAR

NOTE:- The then/else/echo parts of the if statments have been removed
to conserve bandwidth. The `then' logic of the operation is given in
the commant after the `if' statement.

  # Jim Rogers -- 28790...@hplsdv7.hp.com   (compressed)
  if [ `ls -a $dir | wc -l` -eq 2 ];     # then  empty

  # S.Kondakci -- jpc.694747...@avdms8.msfc.nasa.gov
  if ls -a $dir | grep 'total 0';        # then empty
  # modified by Stan Ryckman -- s...@alden.UUCP
  if ls -l $dir | fgrep -x 'total 0';    # then empty

  # David W. Tamkin -- datt...@gagme.chi.il.us
  if [ ". .. * ?" = "`echo .* * ?`" ]    # then not-empty

  # Maarten Litmaath -- ma...@paramount.nikhefk.nikhef.nl  (built-in cmds only)
  DirEmpty() {    # if directory empty -- builtins only
    cd "${1-.}"
    set .* ? *
    case $#$3$4 in
      4\?\*) exit 0
    esac
    exit 1
  }

I am only summerizing -- flames to be deflected

  Anthony Thyssen - (CIT, Griffith University)       anth...@cit.gu.edu.au
------------------------------------------------------------------------------
   Science(n):   Record many facts.            Try to see a pattern.
                     Then make a wrong guess at the next fact.
------------------------------------------------------------------------------



 Fri, 01 Jul 1994 13:12:20 GMT   
 How to determine if directory is empty using /bin/sh
# if $dir is known to exist and is a directory, then:
message=`rmdir $dir 2>&1`
case $message in
   *empty)  echo "Directory is not empty" ;;
   *)       echo "Directory is (er..was) empty" ;;
esac
--
Rahul Dhesi <dh...@cirrus.COM>
UUCP:  oliveb!cirrusl!dhesi
"You're even nuttier than we've come to expect of you." -- Doug Gwyn


 Sat, 02 Jul 1994 07:03:49 GMT   
 How to determine if directory is empty using /bin/sh
anth...@kurango.cit.gu.edu.au (Anthony Thyssen) wrote in
<1992Jan13.051220.6...@kurango.cit.gu.edu.au>:

|   # David W. Tamkin -- datt...@gagme.chi.il.us
|   if [ ". .. * ?" = "`echo .* * ?`" ]    # then not-empty

Either Mr. Thyssen read my suggestion wrong, or he remembered it wrong, or
I made some real doozy of a goof typing it!  If the two tested strings are
equal, then the directory *is* empty.

Maarten Litmaath's was better anyway.

David W. Tamkin  Box 7002  Des Plaines, Illinois  60018-7002  +1 708 518 6769
datt...@gagme.chi.il.us  CIS: 73720,1570  MCI Mail: 426-1818  +1 312 693 0580



 Sat, 02 Jul 1994 01:22:03 GMT   
 How to determine if directory is empty using /bin/sh
After seeing numerous versions of this flash by, I found myself with a
real need to do this.  The various shell solutions seemed kind of
kludgy, so this program (in C -- sorry about that, but I might have
gotten worse flames if I posted it in perl) can be used in your shell
scripts.  The present version counts the number of files in the
directories given on the command line (the default is ".") and both
prints and returns the number.  You can of course delete the printout
and just use the exit status in shell scripts, although you can do this
with "countdir > /dev/null" of course.  Tested on a SGI PI and Sun.

-------------------- cut here ------------------
/* count files in specified directory(ies) */

#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>

/* POSIX uses dirent instead of dir */
#ifdef POSIX
#define DIRENT
#endif POSIX

#ifdef DIRENT
#include <dirent.h>
DIR *dirp, *opendir();
struct dirent *dp, *readdir();
#else DIRENT
#include <sys/dir.h>
int fd;
struct direct dbuf;
#endif DIRENT

main(argc, argv)
int argc;
char **argv;
{
        struct stat sbuf;
        char *name, *sufloc;
        int count = 0;  /* ignore . and .. */

        if(argc > 1)
                while(--argc)
                        count += process( *++argv );
        else
                count = process(".");

        printf("%d\n", count);
        exit(count);

process(directory)      /* count the files in each directory */
char *directory;
{
        int count = -2;
#ifdef DIRENT
        if( !(dirp = opendir(directory)) ) {
#else DIRENT
        if((fd=open(directory, 0)) == EOF) {
#endif DIRENT
                fprintf(stderr, "Cannot open %s\n", directory);
                return(0);
        }
#ifdef DIRENT
        for (dp = readdir(dirp); dp != NULL; dp = readdir(dirp))
#else DIRENT
        while(read(fd,(char *) &dbuf, sizeof(struct direct)) > 0)
#endif DIRENT
                count++ ;
#ifdef DIRENT
        closedir (dirp);
#else DIRENT
        close(fd);
#endif DIRENT
        return(count);
--
William Silvert, Habitat Ecology Division, Bedford Inst. of Oceanography
P. O. Box 1006, Dartmouth, Nova Scotia, CANADA B2Y 4A2.  Tel. (902)426-1577
InterNet Address: silv...@biome.bio.ns.ca



 Sun, 03 Jul 1994 00:50:28 GMT   
 How to determine if directory is empty using /bin/sh
From the keyboard of silv...@cs.dal.ca (Bill Silvert):
:After seeing numerous versions of this flash by, I found myself with a
:real need to do this.  The various shell solutions seemed kind of
:kludgy, so this program (in C -- sorry about that, but I might have
:gotten worse flames if I posted it in perl) can be used in your shell
:scripts.  

I'm sorry, but if it takes C programs to do things as conceptually simple
as testing for empty directories or determining whether one file is newer
than another, something is very seriously wrong with UNIX.  To a shell
programmer, C programs should be the last resort of the unimaginitive.

--tom



 Sun, 03 Jul 1994 02:41:59 GMT   
 How to determine if directory is empty using /bin/sh

Absolutely _marvellous_.  Consider count > 255.  Even worse, any value where count mod 256 == 0.  As a general rule, exiting with a non 0 or 1 exit status
is just a bad idea.

Boyd Roberts                    b...@prl.dec.com

``When the going gets wierd, the weird turn pro...''



 Sun, 03 Jul 1994 03:31:08 GMT   
 
   [ 21 post ]  Go to page: [1] [2]

Similar Threads

1. Q: Sendmail Bug using From: |/bin/tail|/bin/sh

2. #!/bin/sh #!/usr/bin/sh can I do both for 2 diff machines

3. Determining empty directory

4. Ksh: How to determine if a valid directory is empty

5. touch an empty directory: sh vs. csh

6. /bin/sh: recursively comparing directories

7. newbie, /bin/sh script , to go to directory???

8. Determining whether I am using shared text segments under SVR4

9. Determine if login shell using /bin/csh

10. MINICOM and scripts using RUNSCRIPT, EXPECT and /bin/sh for automation


 
Powered by phpBB © 2000, 2002, 2005, 2007 phpBB Group.
Designed by ST Software