Bash Script To Repair Directory and File Ownership

I think the way you are asking is kind of backwards. You don't want to take each folder and then find the user, rather you want to take the user and find their home folder.

#!/bin/bash
while IFS=':' read -r login pass uid gid uname homedir comment; do 
    echo chown $uid:$gid "$homedir"; 
done < /etc/passwd

You will need to remove the echo of course and you will need to run this with root permissions. I also always recommend a while loop instead of a for loop over ls myself. You can save this loop for doing anything with /etc/passwd.


I have to give Kyle Brandt complete credit above. So, if you like this answer below, click the Up triangle on his post to lift his status, please.

However, I improved upon his routine and felt it my duty to post it here and mark it as the final answer.

All I added to Kyle's routine was ensure that we're only touching the home dir, thus the line with the asterisks in it. Then, I ensure that this home dir actually still exists. After that, I do the chown statement. And just like Kyle said -- remove the "echo" keyword and it will actually conduct the task. Then, I added "-R" on the chown to make it work recursively in case the problem might be deeper into one's home dir.

#!/bin/bash

while IFS=':' read -r login pass uid gid uname homedir comment; do
    if [[ "$homedir" = **/home/** ]]; then
        if [ -d "$homedir" ]; then
            echo chown -R $uid:$gid "$homedir";
        fi
    fi
done < /etc/passwd

#!/bin/bash

for f in $( ls /home/ );
  do chown -R $f:yourgroup /home/$f
done

There is no sanity checking in this and I wrote it without any testing, so be careful.

(BTW, the requirement of "no hidden files or folders" will be met by the fact that a hidden file in Unix is just a regular file with a . before it, and .username will not be a valid user for chown).