Hello, I'm trying to write a script which is listing files based on different preferences, like filetype or permissions. All is fine, except for one: I want to list files in /home which has a different owner than the home directory it is in.

Here is an example:
/home/UserA is the directory, and /home/UserA/foobar.txt is the file, that is owned by UserB.
If I would have to use a fixed user, this wouldn't be a problem, as I could just do

find /home/UserA \! -user UserA -exec echo "{}" is not owned by UserA \;

But I don't know, how can I use variables, that modifies the output and the checking based on who's home directory (for a /home/UserB/foobar.txt owned by UserA scenario) it is in. I was thinking about using awk to get the owner of the home directory and the file and compare it, but it doesn't feel right.
Basically I just have to find a way, to cycle through the home directories and replace the 3 UserA in my script, like this:

/home/UserA
/home/UserB
/home/UserC

find /home/UserA \! -user UserA -exec echo "{}" is not owned by UserA \;
find /home/UserB \! -user UserB -exec echo "{}" is not owned by UserB \;
find /home/UserC \! -user UserC -exec echo "{}" is not owned by UserC \;

I would appreciate any idea.

Hello,

What you are trying to do is really what unix shells were designed for. Try this:

for x in `/bin/ls /home`
do
find /home/$x \! -user $x -exec echo "{}" is not owned by $x \;
done

This executes the command
/bin/ls /home
and puts the results in that place in the for loop. The reason you use /bin/ls instead of just ls is that most shells have ls aliased to color the output based on the file type and the color escape sequences wreck havoc with your code...

Thank you for your answer!
With some help, I managed to merge my different codes together, and this is the result:

#!/bin/bash

cd /home
DIR=$( ls -l | awk '{print $3}' )

for dir in $DIR
do
  user=$( basename $dir )
  find $dir ! -user $user -type f -exec echo "{}" is not owned by $user \;
done

It's pretty much the same as yours, except this one uses the actual owners, not the foldername, which is prettier. :-)
However, I like your code, it is nice and compact. :-)

This question has already been answered. Start a new discussion instead.