Finding not empty directories without subdirectories and specific sorting

2

I have a problem with my "homework" on studies.

I have to list all not empty directories from /var and /usr, which do not have subdirectories and their owner is not root user. Also, for each directory I have to show depth in directory tree, i-node number, size, permissions in human-readable and octal formats and absolute path to this directory, and sort it descending by i-node number.

Here is what I've currently done:

find /{us,va}r -type d \! -user root \! -empty -printf "%d %i %k %M %m %u %h/%f\n" | sort -rn

Now I just have to eliminate directories with subdirectories and sort it by i-node number.

So, here comes the questions:

  1. How can I eliminate directories with subdirectories from this list?
  2. How can I sort this list by i-node, which is in the second column?

Thanks for help.

Sebastian Potasiak

Posted 2013-03-24T22:45:03.077

Reputation: 131

Okay, I figured out something like this: find /{us,va}r -links 2 -type d \! -user root \! -empty -printf "%d %i %k %M %m %u %h/%f\n" | sort -rnk 2. Can anyone tell me if it's all right? – Sebastian Potasiak – 2013-03-24T23:52:05.377

I'm curious; how does the 'links' help with finding directories that don't have subdirs? – tink – 2013-03-25T00:20:36.390

2@tink In case of directories, the number of subdirectories is stored as hard links count. By default, every directory (except /) has two subdirectories: '.' and '..' (current directory and parent directory), so if I check if there's only 2 'links' for specified directory, I'll get only directories without actual subdirectories. – Sebastian Potasiak – 2013-03-25T12:01:12.117

If you solved your problem, please consider answering your question and accepting your answer. – Dennis – 2013-03-28T01:50:03.600

Answers

1

So, I was right. All I had to do was to add -links 2 argument to find, so it will output directories with only 2 "hard links" (which are not hard links - it's subdirectory counter and every directory has at least 2 subdirs - '.' and '..') and -k 2 to sort, so it will sort by second column.

Whole command looks like this:

find /{us,va}r -links 2 -type d \! -user root \! -empty -printf "%d %i %k %M %m %u %h/%f\n" | sort -rnk 2

Sebastian Potasiak

Posted 2013-03-24T22:45:03.077

Reputation: 131

0

OK, I think I found a python-based solution to your problem.

Save this snippet as e.g. x.py, and chmod +x x.py

#!/usr/bin/python
import sys
x=[]
for line in sys.stdin:
  x.append(line.rstrip())

y=x[:]
for i in x:
  mark=x.index(i)
  for j in y:
    if i.split()[6]  in j.split()[6]  and i != j:
      if i in y: y.remove(i)

for j in y:
  print j

Then pipe your find command (w/o the links bit) through it, and sort

find /{us,va}r -type d \! -user root \! -empty -printf "%d %i %k %M %m %u %h/%f\n" | x.py | sort -k2,2n

tink

Posted 2013-03-24T22:45:03.077

Reputation: 1 419