Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems.. It's 100% free, no registration required.

I'd like to generate several separate lists for each user in Ubuntu. The lists contains the files and folders belong to each user.

Using the command following list me all the users in the system:

cat /etc/passwd | awk -F: '{print $1;}'

Suppose "user1" is the first result, I'd like to get the list as:

find / -user "user1" > user1.txt

Thus, my problem is how can I get all the lists using commands as little as possible. Thanks in advance.

share|improve this question
add comment

2 Answers

up vote 3 down vote accepted
getent passwd | cut -d: -f1 | while read USER ; do
  echo $USER #use this to show some kind of progress otherwise delete this string
  find / -user $USER > ${USER}.txt 2>/dev/null
done

ps. for more information look at shell loops.

However it is pretty bad idea: you'll need to run find on the whole filesystem as many times as many users you have.

We will be much smarter and do it in another way: we will run find only once and split it's output to a files like this:

find / -printf "%u %p\n" | awk '{print $2 > $1".txt"}'
share|improve this answer
    
You'll need >> if you want more than the last file for each user. –  Kevin Aug 13 '12 at 12:20
    
@Kevin an awk redirection a quite differ from shells one. >> will append awk output to the existing files content, > will empty file and put the full output, not just last line. For details look at staff.science.uu.nl/~oostr102/docs/nawk/nawk_38.html#SEC41 –  rush Aug 13 '12 at 12:43
    
@rush That's really helpful. Thank you very much. –  Allen Koo Aug 13 '12 at 13:18
add comment

At least GNU find has the -fprint variant, with that you can accomplish what you want with one pass of the filesystem using the idiom: find path -user user1 -fprint user1.txt.

First generate the -user and -fprint arguments:

findargs=""
for user in $(cut -d: -f1 /etc/passwd); do
  if [[ -z $findargs ]]; then
    findargs="-user $user -fprint $user.txt";
  else 
    findargs="$findargs -or -user $user -fprint $user.txt"
  fi
done

You're now ready to parse the filesystem:

find path/to/parse $findargs
share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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