59

I'm trying to use GNU find to find only the directories that contain no other directories, but may or may not contain regular files.

My best guess so far has been:

find dir -type d \( -not -exec ls -dA ';' \)

but this just gets me a long list of "."

Thanks!

4

9 Answers 9

98

You can use -links if your filesystem is POSIX compliant (i.e. a directory has a link for each subdirectory in it, a link from its parent and a link to itself, thus a count of 2 links if it has no subdirectories).

The following command should do what you want:

find dir -type d -links 2

However, it does not seems to work on Mac OS X (as @Piotr mentioned). Here is another version that is slower, but does work on Mac OS X. It is based on his version, with a correction to handle whitespace in directory names:

find . -type d -exec sh -c '(ls -p "{}"|grep />/dev/null)||echo "{}"' \;
8
  • @SylvainDefresne, any idea if it will work on NetApp file system over NFS?
    – oz123
    Aug 12, 2013 at 8:57
  • I just used the first version (-links 2) on an NetApp over NFS. So the answer is yes. Aug 1, 2014 at 12:37
  • 1
    Similarly, the simple soln doesn't seem to work in Cygwin (windows 7), but the extended OSx version does
    – Eric B.
    Jan 5, 2015 at 19:16
  • 1
    in my btrfs system directories have link count 1, so this doesn't work. May 19, 2016 at 11:03
  • The replacement string {} should be single-quoted to sh -c, not double quoted, since filenames might contain characters treated specially under double quotes (such as $).
    – eigengrau
    Sep 16, 2017 at 16:10
6

I just found another solution to this that works on both Linux & macOS (without find -exec)!

It involves sort (twice) and awk:

find dir -type d | sort -r | awk 'a!~"^"$0{a=$0;print}' | sort

Explanation:

  1. sort the find output in reverse order

    • now you have subdirectories appear first, then their parents
  2. use awk to omit lines if the current line is a prefix of the previous line

    • (this command is from the answer here)
    • now you eliminated "all parent directories" (you're left with parent dirs)
  3. sort them (so it looks like the normal find output)
  4. Voila! Fast and portable.
3
  • The only problem with this ingenious/portable answer is that, as pointed out here it will fail if any character in the folder name is a regex special character. I've made a small modification and posted my answer here. Jun 29, 2020 at 6:55
  • This will not work if one directory starts with a substring of another. For example, if one leaf directory is called "foo", and another "foobar", this will only show "foobar".
    – Chris Down
    Nov 24, 2020 at 12:46
  • for that matter you can use sed to append a '/' to the end of each line before awk and then remove them after awk Oct 7, 2021 at 5:33
2

@Sylvian solution didn't work for me on mac os x for some obscure reason. So I've came up with a bit more direct solution. Hope this will help someone:

find . -type d  -print0 | xargs -0 -IXXX sh -c '(ls -p XXX | grep / >/dev/null) || echo XXX' ;

Explanation:

  • ls -p ends directories with '/'
  • so (ls -p XXX | grep / >/dev/null) returns 0 if there is no directories
  • -print0 && -0 is to make xargs handle spaces in directory names
1
  • Confused. find -print0 and xargs -0 are also not available out of the box on MacOS; but of course, you can avoid them both with find -exec, like Sylvain's updated answer demonstrates.
    – tripleee
    Sep 18, 2022 at 9:04
2

I have some oddly named files in my directory trees that confuse awk as in @AhmetAlpBalkan 's answer. So I took a slightly different approach

  p=;
  while read c;
    do 
      l=${#c};
      f=${p:0:$l};
      if [ "$f" != "$c" ]; then 
        echo $c; 
      fi;
      p=$c; 
    done < <(find . -type d | sort -r) 

As in the awk solution, I reverse sort. That way if the directory path is a subpath of the previous hit, you can easily discern this.

Here p is my previous match, c is the current match, l is the length of the current match, f is the first l matching characters of the previous match. I only echo those hits that don't match the beginning of the previous match.

The problem with the awk solution offered is that the matching of the beginning of the string seems to be confused if the path name contains things such as + in the name of some of the subdirectories. This caused awk to return a number of false positives for me.

1
  • 1
    Quote your variables when working with files, or things will break.
    – Walf
    May 7, 2021 at 6:05
1

There is an alternative to find called rawhide (rh) that is much easier to use.

For filesystems other than btrfs:

rh 'd && nlink == 2'

For btrfs:

rh 'd && "[ `rh -red %S | wc -l` = 0 ]".sh'

A shorter/faster version for btrfs is:

rh 'd && "[ -z \"`rh -red %S`\" ]".sh'

The above commands search for directories and then list their sub-directories and only match when there are none (the first by counting the number of lines of output, and the second by checking if there is any output at all per directory).

For a version that works on all filesystems as efficiently as possible:

rh 'd && (nlink == 2 || nlink == 1 && "[ -z \"`rh -red %S`\" ]".sh)'

On normal (non-btrfs) filesystems, this will work without the need for any additional processes for each directory, but on btrfs, it will need them. This is probably best if you have a mix of different filesystems including btrfs.

Rawhide (rh) is available from https://raf.org/rawhide or https://github.com/raforg/rawhide. It works at least on Linux, FreeBSD, OpenBSD, NetBSD, Solaris, macOS, and Cygwin.

Disclaimer: I am the current author of rawhide.

2
  • The wc -l variant looks suspicious; perhaps see also useless use of wc
    – tripleee
    Sep 18, 2022 at 10:21
  • Yes. The wc can be avoided. That's what the second version demonstrates. Instead of wc counting the lines of rh output and the shell comparing that against zero, the shell just measures the length of any rh output.
    – raf
    Sep 20, 2022 at 9:12
0

What about this one ? It's portable and it doesn't depend on finnicky linking counts. Note however that it's important to put root/folder without the trailing /.

find root/folder -type d | awk '{ if (length($0)<length(prev) || substr($0,1,length(prev))!=prev) print prev; prev=($0 "/") } END { print prev }'
0

Here is solution which works on Linux and OS X:

find . -type d -execdir bash -c '[ "$(find {} -mindepth 1 -type d)" ] || echo $PWD/{}' \; 

or:

find . -type d -execdir sh -c 'test -z "$(find "{}" -mindepth 1 -type d)" && echo $PWD/{}' \;
1
  • Shouldn't that be -maxdepth?
    – Tom Hale
    Feb 20, 2021 at 12:22
0

This awk/sort pipe works a bit better than the one originally proposed in this answer, but is heavily based on it :) It will work more reliably regardless of whether the path contains regex special characters or not:

find . -type d | sort -r | awk 'index(a,$0)!=1{a=$0;print}' | sort

Remember that awk strings are 1-indexed instead of 0-indexed, which might be strange if you're used to working with C-based languages.

If the index of the current line in the previous line is 1 (i.e. it starts with it) then we skip it, which works just like the match of "^"$0.

3
  • This will fail to match directories whose name is a prefix of a sibling directory. E.g. if you have paths /a/a and /a/ab, then /a/a will not be reported.
    – Ruud
    Aug 24, 2020 at 20:18
  • How about using -depth option of find like this: find . -depth -type d | awk 'index(a,$0)!=1{a=$0;print}'
    – Chubler_XL
    Aug 1, 2022 at 23:59
  • This will obviously fail on directory names which contain newlines.
    – tripleee
    Sep 18, 2022 at 9:00
0

My 2 cents on this problem:

#!/bin/bash
(
while IFS= read -r -d $'\0' directory
do
    files=$(ls -A "$directory" | wc -l)
    if test $files -gt 0 
    then
        echo "$directory"
    fi
done < <(find . -type d -print0)
) | sort | uniq

It uses a subshell to capture output from the run, and lists directories which have files.

4
  • I don't believe the subshell is necessary or useful, actually. The -print0 option to find is a GNU extension, and not properly portable. Using ls in scripts is always suspicious.
    – tripleee
    Sep 19, 2022 at 14:26
  • This was on mywiki.wooledge.org/BashFAQ/020.
    – Niloct
    Sep 19, 2022 at 14:54
  • The subshell is needed to capture the output, otherwise all directories are echoed as listed.
    – Niloct
    Sep 19, 2022 at 14:55
  • Redirecting done into the pipe suffices eminently for that.
    – tripleee
    Sep 19, 2022 at 15:12

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.