I want to create a script to delete any directories with numeric groups.
What I have so far captures and analyzes the group:

for x in `/usr/bin/ls -l /var/indexes | sort -k3,3 | tr -s " " | cut -f3 -d " "`
if [[ $x =~ $re ]] ; then
   echo "found one $x"

The problem is, the actual name of the directory is in another column.
Here is one line of the ls output:

drwxr-sr-x. 3                     3966 root 4096 Oct 20 16:29 dirname

So I need to iterate through the ls results and capture both the group (in this case 3966) and the directory name (in this case dirname) so I can form an rm -rf command to remove it when I find a blank one.
How would I do that?
Thanks in advance.


2 Answers 2


Wouldn't it be easier to use find with the -nogroup flag? For example:

find /var/indexes -nogroup

If you want to base the script around ls then awk is tool I'd use to select columns.

  • Getting the columns to print is not a problem. Getting the columns into the for loop and the if statement and the rm command is the question. I don't see any info on the internet on the -nogroup option for find ... and the man entry is useless.
    – xivix
    Dec 1, 2014 at 23:07
  • 2
    man gnu find - -nogroup: No group corresponds to file's numeric group ID. The trick with find is to know that there are two fairly common versions, the GNU, and the BSD. There are lots of differences between the two.
    – Zoredache
    Dec 1, 2014 at 23:23

You don't really want to do this in bash, but because you asked, this is how you could split it up.

for x in `/usr/bin/ls -l --time-style=+'%s' /var/indexes | sort -k3,3 | awk '{print $3 $7}'`
read -A nm <<< "$x"
if [[ ${nm[0]} =~ $re ]] ; then
   echo "found one " ${nm[1]}

It's easier in awk like so:

/usr/bin/ls -l --time-style=+'%s' /var/indexes | sort -k3,3 | awk '($3 ~ /^[0-9]+$/){print $7}'

Really, the right solution is find w/ -nogroup as suggested by Paul H..

  • --time-style assumes gnu coreutils. I inferred this because of the date format. This won't work on some unicies like HP-UX. Dec 1, 2014 at 23:11
  • I'm all for simplicity but I can't find any info on the -nogroup option on the net ... and the man entry is useless. I'm interested if you can help.
    – xivix
    Dec 1, 2014 at 23:12
  • man find , ctrl-f on the website or / from the shell, type nogroup ? What distribution is this? Dec 1, 2014 at 23:15
  • scientific Linux 6.5
    – xivix
    Dec 1, 2014 at 23:21
  • I already looked in the man entry ... all it says is ... No group corresponds to file's numeric group ID. ... which is useless to me
    – xivix
    Dec 1, 2014 at 23:22

You must log in to answer this question.