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.
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.
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.
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).
This might help
Use
getent
to get the user name, group name, and home directory of each user whose user ID is greater than or equal to 500, and apply them viachown -R
. Also, nowadays it'suser:group
.for i in
ls -l /home/ | awk '{print $3}'
;do chown -R $i /home/$i;donefor i in
ls -l /home/ | awk '{print $4}'
;do chgrp -R $i /home/$i;done