6

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.

6 Answers 6

8

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.

8

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 
5
#!/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).

3

This might help

 #!/bin/bash for file in `ls -a | grep -v '^\.'` do if [[ -d $file ]] then fowner=`ls -ld $file | nawk '{print $3}'` fgroup=`ls -ld $file | nawk '{print $4}'` chown -R $fowner:$fgroup $file fi done 
1

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 via chown -R. Also, nowadays it's user:group.

1

for i in ls -l /home/ | awk '{print $3}';do chown -R $i /home/$i;done
for i in ls -l /home/ | awk '{print $4}';do chgrp -R $i /home/$i;done

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.