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

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.


You can use the basename command to provide the last component of a path

for dir in /home/*
do
    if [ -d "$dir" ]
    then
        username=$(basename "$dir")
        chown -R "$username" "$dir"
    fi
done

although I would initially run it as

for dir in /home/*
do
    if [ -d "$dir" ]
    then
        username=$(basename "$dir")
        echo "chown -R $username $dir"
    fi
done

to make sure it was sane.