find files with bad ownership

This is a simple way of finding files that have been created by the wrong user in a directory. It happens usually when

  • you use the sudo command
  • someone deliberatly has altered a file protection

Recently I cause the 1st problem by forcing an app to start using

sudo /opt/x/y/z/startApp

However when I then rebooted the machine and tried running the command as a non-priv user then I found I could not write to certain files.

nice find command

My username has the UIC of 503 - you can check this in /etc/passwd, if you are not sure of what I am talking about - you had best not continue - as what follows can really mess up your system.

I want to see the files in the /opt/x/... directory structure that I suspect have the wrong ownership.

find /opt/x -printf '%U-%h/%f\n' | grep -v ^503

This means

  • find me file from /opt/xa and downwards
  • print the
    • %U - userid
    • %h - file path (no last /)
    • / - Add a /
    • %f - a filename

then

  • | pipe the output to
  • grep
    • -v NOT
    • ^503 Starting with 503

#Build a Fix Command file

Assuming that the previous command has given you some bad files - you will not want to fix these files. Yes you could just do a chown -R but lets try and be more delicate with the file system that that ( at least for the moment).

##Use Initial command

Adding a little sed processing to the output

 sed -e 's/^0-.\//chown bob:thebuilder /g' >

Meaning

  • sed - Stream Editor
  • -e Expression
  • 's/ Substitute
  • ^0 - Starting with 0
    • Followed by a dash
  • . Followed by a period
  • \/ Followed by a /
  • / Change to
  • chown user:group
  • /g globally
  • ' end of substitute command

#So all together this is

bash find . -printf '%U-%h/%f\n' | grep -v ^503 | sed -e 's/^0-\.\//chown bob:thebuilder /g' > t.sh sudo t.sh