Linux – Script to run chown on all folders and setting the owner as the folder name minus the trailing /

bashlinuxshellssh

Some numpty ran chown -R username. in the /home folder on our webserver thinking he was in the desired folder. Needless to say the server is throwing a lot of wobbelys.

We have over 200 websites and I don't want to chown them all individually so I'm trying to make a script that will change the owner of all the folders to the folder name, without the trailing /.

This is all I have so far, once I can remove the / it will be fine, but I'd also like to check if the file contains a . in it, and if it doesn't then run the command, otherwise go to the next one.

#!/bin/bash
for f in *

do

    test=$f;
    #manipluate the test variable
    chown -R $test $f

done

Any help would be great!

Thanks in advance!

Best Answer

Assuming that all folders in the /home/ directory represents user names, you can use:

for dir in /home/*/; do
    # strip trailing slash
    homedir="${dir%/}"
    # strip all chars up to and including the last slash
    username="${homedir##*/}"

    case $username in
    *.*) continue ;; # skip name with a dot in it
    esac

    chown -R "$username" "$dir"
done

I suggest to run a test loop before, checking whether the user name actually matches a home directory.

This AWK command retrieves the home directory for a given user.

awk -F: -v user="$username" '{if($1 == user){print $6}}' < /etc/passwd

Checking this result against the existing home dir is an exercise for the reader.

Related Topic