harris@catt.ncsu.edu (Michael Harris) (03/30/91)
When I am running a shell script, how can I tell when a directory is empty? I tried looking at the output of ls -a but it includes . and .. Suggestions anyone? __ _ ___ ___ Michael Harris - harris@catt.ncsu.edu // _ | / \ | | Computer and Technologies Theme Program // /||\/||/ _ /| |__ / /_\ | | North Carolina State University \X/ /-|| ||\_|/-|
fitz@mml0.meche.rpi.edu (Brian Fitzgerald) (03/30/91)
Michael Harris writes: >When I am running a shell script, how can I tell when a directory is empty? Try: if [ ! "`ls -A $name`" ] ; then
harris@garfield.catt.ncsu.edu (Michael Harris) (03/31/91)
Thanks to all that helped. I wouldn't have asked such a simple question, but the -A option was not in the man page for ls on our system! It does work though. Strange, isn't it? __ _ ___ ___ Michael Harris - harris@catt.ncsu.edu // _ | / \ | | Computer and Technologies Theme Program // /||\/||/ _ /| |__ / /_\ | | North Carolina State University \X/ /-|| ||\_|/-|
hunt@dg-rtp.rtp.dg.com (Greg Hunt) (03/31/91)
In article <1991Mar30.040400.13893@ncsu.edu>, harris@catt.ncsu.edu (Michael Harris) writes: > When I am running a shell script, how can I tell when a directory is empty? > I tried looking at the output of ls -a but it includes . and .. > Suggestions anyone? If the only files that are shown by an "ls -la" of a directory are "." and "..", then the directory is "empty". The "." file is just a shorthand way of saying "the current directory", so it refers to the directory itself. The ".." file is a shorthand way of saying "the parent directory of this directory", so it refers to the superior directory. If you look closely at an "ls -lia" listing, you'll notice that the "." and ".." files are really hard links to the current directory and the parent directory, respectively. All directories are automatically created with the "." and ".." files in them, and you cannot remove those files yourself. They will be deleted when the directory itself is deleted. Once ls shows that "." and ".." are the only files remaining in a directory, then you can delete the directory using the rmdir command. Telling whether a directory is empty from a script should be possible by looking at the size of the directory itself. If the directory size is zero, then the directory is empty. Otherwise, it contains some files. You should check this out on your system to make sure it holds true for the flavor of UNIX that you're using. If it does then you can see if a directory is empty this way (using the Bourne shell): if [ -d file ] ; then echo "File is a directory and exists" if [ -s file ] ; then echo "Directory has some files in it" else echo "Directory is empty" fi else if [ -f file ] ; then echo "File is a regular file and exists" else echo "File does not exist" fi fi The "-d file" is a test that returns true (zero) if the file exists and is a directory. The "-s file" test returns true if the file exists and has a size greater than zero. The "-f file" test returns true if the file exists and is a regular file. Look at the man pages for test or sh to see what other tests you can use as conditions inside if's, etc. Enjoy! -- Greg Hunt Internet: hunt@dg-rtp.rtp.dg.com DG/UX Kernel Development UUCP: {world}!mcnc!rti!dg-rtp!hunt Data General Corporation Research Triangle Park, NC, USA These opinions are mine, not DG's.
sog@bierstadt.scd.ucar.edu (Steve Gombosi) (03/31/91)
Wouldn't it be easier to pipe the output of "ls -la" through "wc -l" and test for the output being equal to two? Since an empty directory contains only "." and "..", and "ls -la" (at least on my system) provides a "Totals" line, the output looks like this: %ls -la empty_directory total 2 drwxr-xr-x 2 sog 512 Mar 30 19:07 . drwxr-xr-x 11 sog 1024 Mar 30 19:10 .. %ls -la empty_directory|wc -l 3 So, if `ls -la directory_name|wc -l` != 3, the directory has something in it. Of course, if it's less than three, something is REALLY screwed up...
fitz@mml0.meche.rpi.edu (Brian Fitzgerald) (04/01/91)
>>Michael Harris writes: >>>When I am running a shell script, how can I tell when a directory is empty? I replied: >>Try: >> >> if [ ! "`ls -A $name`" ] ; then Michael Stefanik writes: >$ ls -A /tmp >ls: illegal option -- A >usage: ls -RadCxmnlogrtucpFbqisfLk [files] > >How about this instead? > > if [ `ls $dir | wc -l` = 0 ] ; then > >I think that this would work rather consistently, regardless of the >pecularities of /bin/ls. %-( [22] mml0 fitz /tmp% mkdir foo [23] mml0 fitz /tmp% ls foo [24] mml0 fitz /tmp% touch foo/.hidden [25] mml0 fitz /tmp% ls foo [26] mml0 fitz /tmp% #-) [30] mml0# cd /tmp /tmp [31] mml0# ls foo .hidden
les@chinet.chi.il.us (Leslie Mikesell) (04/02/91)
In article <1991Mar30.040400.13893@ncsu.edu> harris@catt.ncsu.edu (Michael Harris) writes: >When I am running a shell script, how can I tell when a directory is empty? >I tried looking at the output of ls -a but it includes . and .. Usually the reason I want to know this is that I plan to do something to all the visible files if there are any, so something like this will work using the builtin "echo" command and only require the directory to be read once. LIST=`echo *` if [ "*" = "$LIST" ] then : # no files - do nothing else for i in $LIST do .... # commands to process files done fi Les Mikesell les@chinet.chi.il.us
sog@bierstadt.scd.ucar.edu (Steve Gombosi) (04/02/91)
`ls $dir|wc -l` doesn't always work. A straight "ls" won't catch the existence of "hidden" files (i.e., files whose name begins with "."). You could have megabytes worth of such files and STILL think the directory was empty. You have to use the -a option to see these files.
dmturne@PacBell.COM (Dave Turner) (04/03/91)
In article <=-#g4!g@rpi.edu> fitz@mml0.meche.rpi.edu (Brian Fitzgerald) writes: >>>Michael Harris writes: >>>>When I am running a shell script, how can I tell when a directory is empty? >> >> if [ `ls $dir | wc -l` = 0 ] ; then >> Use the form of ls that gives all entries in a directory including . and .. . Check for a count of two. For System V and the Bourne shell if [ `ls -a $dir | wc -l` -eq 2 ] then echo empty else echo not empty fi -- Dave Turner 415/823-2001 {att,bellcore,sun,ames,decwrl}!pacbell!dmturne
jik@athena.mit.edu (Jonathan I. Kamens) (04/03/91)
In article <1991Mar30.225406.20493@dg-rtp.dg.com>, hunt@dg-rtp.rtp.dg.com (Greg Hunt) writes: |> Telling whether a directory is empty from a script should be possible |> by looking at the size of the directory itself. If the directory size |> is zero, then the directory is empty. Otherwise, it contains some |> files. You should check this out on your system to make sure it holds |> true for the flavor of UNIX that you're using. Um, I can't imagine this being true for *any* remotely normal flavor of Unix. I just did the following tests on both a BSD-derived and a SysV-derived system: 1) Create a new, empty directory. Check its size. Cd into it and run the following: if [ -s . ]; then echo "Directory has some files in it." else echo "Directory is empty." fi and see what happens. 2) Create a bunch of files in the directory. Remove them all. Check the directory's size again. In the first case, the size of the newly created directory was non-zero, just as I expected, and the if statement printed out "Directory has some files in it," although I hadn't added any. How can the directory be empty when it has to store entries for "." and ".." in it? In the second case, the directory did not shrink when the files were deleted. Directories grow. I'm not even convinced that fsck shrinks empty dirctories; I believe the only way to shrink a directory with lots of empty entries in it is to create a new directory, mv the files from the old directory into the one one, and remove the old directory. If you tried what you posted on a system and it worked, I'd be very interested in knowing what kind of Unix it was and what type of filesystem it's running. Does it store the "." and ".." directory entries somewhere special, or does it fake them without putting them in the filesystem, or does "size" mean something special in the context of directories, or what? -- Jonathan Kamens USnail: MIT Project Athena 11 Ashford Terrace jik@Athena.MIT.EDU Allston, MA 02134 Office: 617-253-8085 Home: 617-782-0710
asg@sage.cc.purdue.edu (Bruce Varney) (04/04/91)
In article <1991Apr3.142150.4445@athena.mit.edu> jik@athena.mit.edu (Jonathan I. Kamens) writes: }In article <1991Mar30.225406.20493@dg-rtp.dg.com>, hunt@dg-rtp.rtp.dg.com (Greg Hunt) writes: }|> Telling whether a directory is empty from a script should be possible }|> by looking at the size of the directory itself. If the directory size }|> is zero, then the directory is empty. Otherwise, it contains some }|> files. You should check this out on your system to make sure it holds }|> true for the flavor of UNIX that you're using. } } Um, I can't imagine this being true for *any* remotely normal flavor of Unix. } You're right Jon [ :-( gasp!, did I really say that? ] But why are you all making this so hard????? Its easy. do this: ---isempty--- #!/bin/sh dir=$1 num1=`ls -aF $dir | grep -v "/$" | wc -l` num2=`expr \`ls -lad $dir | cut -c12-13\` - 2 ` num=`expr $num1 + $num2` if [ $num = "0" ] then echo The directory is empty else echo The directory is not empty fi ---isempty--- then just do isempty directory_in_question and it will tell you if the dir is empty or not }-- }Jonathan Kamens USnail: ^^^^^^ Get the UShammer!!! Bruce --------- sar.casm \'sa:r-.kaz-*m\ \sa:r-'kas-tik\ \-ti-k(*-)le-\ n [F sarcasme, fr. LL sarcasmos, fr. Gk sarkasmos, fr. sarkazein to tear flesh, bite the lips in rage, sneer, fr. sark-, sarx flesh; akin to Av thwar*s to cut] 1: a cutting, hostile, or contemptuous remark : GIBE 2: the use of caustic or ironic language - sar.cas.tic aj ### ## Courtesy of Bruce Varney ### # aka -> The Grand Master # asg@sage.cc.purdue.edu ### ##### # PUCC ### # ;-) # # ;'> # ##
urban@cbnewsl.att.com (john.urban) (04/04/91)
>In an article, mml0.meche.rpi.edu!fitz (Brian Fitzgerald) writes: >Michael Harris writes: >>When I am running a shell script, how can I tell when a directory is empty? > >Try: > > if [ ! "`ls -A $name`" ] ; then Why not just run rmdir $directory and if it works, then the directory was empty. ie. if [ -d test1 ] then rmdir test1 if [ -d test1 ] then echo Not empty directory test1 else mkdir test1 echo Empty directory test1 fi fi Sincerely, John Urban
ask@cbnews.att.com (Arthur S. Kamlet) (04/04/91)
In article <1991Apr3.211052.893@cbnewsl.att.com> urban@cbnewsl.att.com (john.urban) writes: >>>When I am running a shell script, how can I tell when a directory is empty? > >Why not just run rmdir $directory and if it works, then the directory was empty. >if [ -d test1 ] >then rmdir test1 > if [ -d test1 ] > then echo Not empty directory test1 > else mkdir test1 > echo Empty directory test1 > fi >fi If the reason for knowing if a directory is empty is to know if it can be removed, then rmdir test1 is sufficient. Note: The above code will create a new test1 directory which could be smaller than the original test1 directory. All of these scripts, of course, assume the directory and the parent directory have correct read/write/search permissions for the user. -- Art Kamlet a_s_kamlet@att.com AT&T Bell Laboratories, Columbus
hunt@dg-rtp.rtp.dg.com (Greg Hunt) (04/04/91)
In article <1991Apr3.142150.4445@athena.mit.edu>, jik@athena.mit.edu (Jonathan I. Kamens) writes: > In article <1991Mar30.225406.20493@dg-rtp.dg.com>, hunt@dg-rtp.rtp.dg.com (Greg Hunt) writes: > |> Telling whether a directory is empty from a script should be possible > |> by looking at the size of the directory itself. If the directory size > |> is zero, then the directory is empty. Otherwise, it contains some > |> files. You should check this out on your system to make sure it holds > |> true for the flavor of UNIX that you're using. > > Um, I can't imagine this being true for *any* remotely normal flavor of > Unix. Well, DG/UX does it this way, and it's a pretty modern UNIX. It's also completely compliant with system 5.4. > I just did the following tests on both a BSD-derived and a SysV-derived > system: > > 1) Create a new, empty directory. Check its size. Cd into it and run the > following: > > if [ -s . ]; then > echo "Directory has some files in it." > else > echo "Directory is empty." > fi > > and see what happens. It reports "Directory is empty", just as I expected it to. That's because the size of the directory file itself is zero bytes. > 2) Create a bunch of files in the directory. Remove them all. Check the > directory's size again. It still reports the size as zero bytes after the files have been removed, just as expected. > In the first case, the size of the newly created directory was non-zero, > just as I expected, and the if statement printed out "Directory has some files > in it," although I hadn't added any. How can the directory be empty when it > has to store entries for "." and ".." in it? Some UNIX'es store . and .. in the inode of the directory instead of as files in the directory. They look to all the world like hard links to the current directory and to the parent directory. They show up on ls -la listing just as expected. It makes creating directories easier. Some, maybe most from what you're saying, UNIX'es don't do it this way. Some do. > In the second case, the directory did not shrink when the files were > deleted. Directories grow. I'm not even convinced that fsck shrinks empty > dirctories; I believe the only way to shrink a directory with lots of empty > entries in it is to create a new directory, mv the files from the old > directory into the one one, and remove the old directory. I'd agree that what you said would be necessary on systems that don't grow and shrink directory entries dynamically. > If you tried what you posted on a system and it worked, I'd be very > interested in knowing what kind of Unix it was and what type of filesystem > it's running. Does it store the "." and ".." directory entries somewhere > special, or does it fake them without putting them in the filesystem, or does > "size" mean something special in the context of directories, or what? It's DG/UX, which is completely compliant with system 5.4. It runs the DG/UX filesystem. The . and .. entries are stored in the inode of the directory itself. That makes creating directories easier. The size of a directory file means the same thing as it does for other files, and since . and .. aren't stored as files in the directory, they don't show up in the space used by the directory. I was aware that other UNIX'es do things differently, and that's why I suggested that the person that asked the question try out his system to see how it functions. Sorry for all the confusion. -- Greg Hunt Internet: hunt@dg-rtp.rtp.dg.com DG/UX Kernel Development UUCP: {world}!mcnc!rti!dg-rtp!hunt Data General Corporation Research Triangle Park, NC, USA These opinions are mine, not DG's.
paul@prcrs.prc.com (Paul Hite) (04/05/91)
In article <1991Apr3.142150.4445@athena.mit.edu>, jik@athena.mit.edu (Jonathan I. Kamens) writes: > In article <1991Mar30.225406.20493@dg-rtp.dg.com>, hunt@dg-rtp.rtp.dg.com (Greg Hunt) writes: > |> Telling whether a directory is empty from a script should be possible > |> by looking at the size of the directory itself. If the directory size > |> is zero, then the directory is empty. Otherwise, it contains some > |> files. You should check this out on your system to make sure it holds > |> true for the flavor of UNIX that you're using. > > Um, I can't imagine this being true for *any* remotely normal flavor of Unix. > Well Jonathan, HP's old 9000/500 series did behave that way and it was *remotely* normal. The 500 used a screwy filesystem which HP called SDF (Structured Directory Format). SDF was somewhat like the old Sys V filesystem. But the inode was larger and contained some extra fields. It had a creation date and parent directory among other things. The parent directory field was used only if the inode was for a directory. Newly created directories were indeed totally empty. The kernel handled "." and ".." specially. If you used opendir(3) and friends, you would see a "." and "..". Also ls would report them. But if you opened the directory and started reading and expected to find a . and .. entries, you would lose. The creation date was largely useless. The kernel would put the date in the inode, but there was no way access it via any system call. It was accessible via the raw device of course. And HP did have a custom fsdb that could display and modify it. HP's current incarnation of HP-UX still has some limited support for SDF. Paul Hite PRC Realty Systems McLean,Va uunet!prcrs!paul (703) 556-2243 You can't tell which way the train went by studying its tracks.
goudreau@larrybud.rtp.dg.com (Bob Goudreau) (04/05/91)
In article <1991Apr3.142150.4445@athena.mit.edu>, jik@athena.mit.edu (Jonathan I. Kamens) writes: > In article <1991Mar30.225406.20493@dg-rtp.dg.com>, hunt@dg-rtp.rtp.dg.com (Greg Hunt) writes: > |> If the directory size > |> is zero, then the directory is empty. Otherwise, it contains some > |> files. You should check this out on your system to make sure it holds > |> true for the flavor of UNIX that you're using. > > Um, I can't imagine this being true for *any* remotely normal > flavor of Unix.... > How can the directory be empty when it > has to store entries for "." and ".." in it? Because the directory does not *have* to store entries for "." and ".." in it. That's just an implementation detail; various UNIXes choose to implement things differently. Remember, POSIX.1 doesn't require anything particular about the implementation of directories; only the *interfaces* are specified (readdir, mkdir, etc.). Greg's example was on a system running DG/UX, which happens to implement directory files by keeping "." and ".." info in the inode itself. The implementation is unimportant, however -- all the standard interfaces (POSIX.1's readdir(), SVR4's getdents(), etc.) all return "." and ".." info as if there actually were on-disk entries for those names. As Greg noted, check your system's documentation if you are interested in the details of implementation. > In the second case, the directory did not shrink when the files were > deleted. Directories grow. I'm not even convinced that fsck shrinks > empty dirctories; I believe the only way to shrink a directory with > lots of empty entries in it is to create a new directory, mv the > files from the old directory into the one one, and remove the old > directory. Again, this sort of behavior is implementation-specific. Check your system documentation. DG/UX happens to be able to shrink directories dynamically; other systems differ. ---------------------------------------------------------------------- Bob Goudreau +1 919 248 6231 Data General Corporation goudreau@dg-rtp.dg.com 62 Alexander Drive ...!mcnc!rti!xyzzy!goudreau Research Triangle Park, NC 27709, USA
cudcv@warwick.ac.uk (Rob McMahon) (04/05/91)
I know this is getting silly, but In article <572@bria> uunet!bria!mike writes: >True enough; I didn't account for hidden files. Okay, then how about this >instead? > > if [ `ls $dir/* $dir/.[!.]* | wc -l` = 0 ] ; then touch ..hidden Oops. Also not all versions of sh have the [!...] construction. I think the only sensible way to do this is [ `ls -a $dir | wc -l` = 2 ]; that should be pretty portable. >And under systems that do have this behaviour, I have seen them list . and .. >along with everything else. You sure ? The ls's I've seen that change behaviour for root list everything but . and .., a la -A. Cheers, Rob -- UUCP: ...!mcsun!ukc!warwick!cudcv PHONE: +44 203 523037 JANET: cudcv@uk.ac.warwick INET: cudcv@warwick.ac.uk Rob McMahon, Computing Services, Warwick University, Coventry CV4 7AL, England
root@homer.UUCP (Marc Brumlik) (04/12/91)
In article <9424@mentor.cc.purdue.edu> asg@sage.cc.purdue.edu (Bruce Varney) writes:
->But why are you all making this so hard?????
->Its easy.
->do this:
->---isempty---
->#!/bin/sh
->dir=$1
->num1=`ls -aF $dir | grep -v "/$" | wc -l`
->num2=`expr \`ls -lad $dir | cut -c12-13\` - 2 `
->num=`expr $num1 + $num2`
->if [ $num = "0" ]
->then
-> echo The directory is empty
->else
-> echo The directory is not empty
->fi
->---isempty---
it can be even easier than this... how about:
cd $1
files=`echo *`
if [ "Z$files" = "Z" ]
then echo "empty"
else echo "not empty"
fi
--
..{util20,obdient}!homer!marc Marc Brumlik, Tailored Software, Inc.
Wheaton, IL Voice: 708 668 9947
pauld@stowe.cs.washington.edu (Paul Barton-Davis) (04/16/91)
In article <900@homer.UUCP> root@homer.ORG (Marc Brumlik) writes: >it can be even easier than this... how about: [ deleted ] why not just: if [ "`cd $1 ; echo *`" ] ; then echo "not empty" else echo "empty" fi -- Paul Barton-Davis <pauld@cs.washington.edu> UW Computer Science Lab ``to shatter tradition makes us feel free''
sog@bierstadt.scd.ucar.edu (Steve Gombosi) (04/16/91)
In article <1991Apr15.180550.14750@beaver.cs.washington.edu> pauld@cs.washington.edu (Paul Barton-Davis) writes: >In article <900@homer.UUCP> root@homer.ORG (Marc Brumlik) writes: > >>it can be even easier than this... how about: > [ deleted ] > >why not just: > > if [ "`cd $1 ; echo *`" ] ; then > echo "not empty" > else > echo "empty" > fi For an example of why this doesn't work, may I submit the following "script" output: Script started on Mon Apr 15 17:56:31 1991 bierstadt% mkdir dummy bierstadt% cd dummy bierstadt% cat>.xx1 ^D bierstadt% cat>.xx2 ^D bierstadt% ls bierstadt% ls -a . .. .xx1 .xx2 bierstadt% echo * echo: No match. bierstadt% exit bierstadt% script done on Mon Apr 15 17:57:24 1991 As you can see, directory "dummy" is NOT empty, but both a regular "ls" and "echo *" show it to be "empty". -- -- Steve Gombosi sog@bierstadt.ucar.edu | "The relationship between employer and employee, sgombosi@isis.cs.du.edu | like that between master and slave, is demeaning | to both" -- Edward Abbey
bernie@metapro.DIALix.oz.au (Bernd Felsche) (04/18/91)
I suppose this might have been mentioned before.... If you can write to the parent, then try to rmdir it. rmdir will fail (to the best of my knowledge/experience) if there's anything in the directory. rmdir $dir && mkdir $dir || echo $dir not empty 1>&2 Good enough? Thought not! -- Bernd Felsche, _--_|\ #include <std/disclaimer.h> Metapro Systems, / sale \ Fax: +61 9 472 3337 328 Albany Highway, \_.--._/ Phone: +61 9 362 9355 Victoria Park, Western Australia v Email: bernie@metapro.DIALix.oz.au
rodney@tyrell.stgt.sub.org (Rodney Volz) (04/22/91)
In article <1991Apr18.054735.6733@metapro.DIALix.oz.au> bernie@metapro.DIALix.oz.au (Bernd Felsche) writes: > >rmdir $dir && mkdir $dir || echo $dir not empty 1>&2 What about permissions? -Rodney -- Rodney Volz - 7000 Stuttgart 1 - FRG ============> ...uunet!mcsun!unido!gtc!aragon!tyrell!rodney <============= rodney@tyrell.gtc.de * rodney@delos.stgt.sub.org * rodney@mcshh.hanse.de \_____________ May your children and mine live in peace. ______________/
rvp@softserver.canberra.edu.au (Rey Paulo) (04/25/91)
In article <1991Apr18.054735.6733@metapro.DIALix.oz.au> bernie@metapro.DIALix.oz.au (Bernd Felsche) writes:
[ stuff deleted ]
Is there any system call or library routine in UNIX which tests whether
a directory is empty?
Thanx.
--
Rey V. Paulo | Internet: rvp@csc.canberra.edu.au
University of Canberra | I am not bound to please thee with my answer.
AUSTRALIA | -Shylock, in "The Merchant of Venice"
------------------------------+----------------------------------------------