Shell Find – Locate Directories Without Subdirectories

directoryfindkshlsshell

I'm writing script is ksh. Need to find all directory names directly under the current directory which contain only files, not subdirectories.

I know that I could use ls -alR and recursively parse output for the first letter in the first field (d for a directory). I think awk is the best way to parse and find.

For example, a simple ls -al output in the current directory:

   drwxr-xr-x  22 af      staff    748 18 Mar 22:21 .
   drwxr-xr-x   5 root    admin    170 17 Mar 18:03 ..
   -rw-------   1 af      staff      3 17 Mar 16:37 .CFUserTextEncoding
   drwxr-xr-x   5 af      staff    170 17 Mar 17:12 Public
   drwxr-xr-x   9 af      staff    306 18 Mar 17:40 Sites
   -rw-------   1 af      staff      3 17 Mar 16:37 textd
   …

There are 2 directories in this output: Public and Sites. The directory Public doesn't contain subdirectories, but Sites does. There are 3 subdirectories in Sites. So I need to echo only the directories which don't contain directories in them. In my case, this is only Sites.

Best Answer

You don't need to use awk at all. Use the built-in tests that ksh provides, something like this:

#!/bin/ksh

for NAME in *
do
    FOUND=no
    if [[ -d $NAME && $NAME != '.' && $NAME != '..' ]]
    then
        for SUBNAME in $NAME/*
        do
            if [[ -d $SUBNAME ]]
            then
                FOUND=yes
                break
            fi
        done
        if [[ $FOUND == no ]]
        then
            echo Found only files in $NAME
        fi
    fi
done

That little script looks in all the directories in the current directory, and tells you if they only contain files, no sub-directories.

Related Question