Linux – Bash Script To Repair Directory and File Ownership

bashdirectorylinuxpermissions

My client had me deploy some folders out to a bunch of home directories for his customer websites. I did this with a Bash script, but it ended up using the root account permissions.

How do I make a Bash script that takes each folder under /home/user (not hidden files or folders), gets the user and group ownership of that folder, and then does a chown -R {user}.{group} /home/user?

The servers are running CentOS Linux.

Best Answer

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.

Related Topic