2

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.

3
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"}'
3
  • 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
1

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

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.