Removing old user directories that are no longer Users in /etc/passwd

I am new to shell scripting, and have not done much programming in several years. So I am very rusty at this at best. I know my way around the linux command line, but actually scripting is something I have not done too much of.

I have been tasked to come up with a script that will pull all users from /etc/passwd. Then I need to find all the user directories in /home. If there is a user directory in /home that does not have a corresponding I need to delete that directory and everything in it.

I know I can use

awk -F: '{ if ($3 > 999) { print $1 }}' /etc/passwd 

To find all the users above userid 999.

I know

ls /home/

will pull up all the different user directories.

My thinking of how the script should logically run is something as follows.

Find all users in /etc/passwd above userid 999
find all users in /home
compare users in /home to users in /etc/passwd
remove all user directories in /home who are not in /etc/passwd

So any help with this would be greatly appreciated.

I'm worried about this 'greater than 999' requirement. It sounds backwards. Would it be okay to delete /home/root since root's uid is less than 999? Probably not.

I suspect you're supposed to consider the ownerships of the home directories themselves, right? Their UID's will be preserved even when the user's deleted.

What's your system? What's your shell?

Shell is bash. Systems are Redhat, Centos, and Ubuntu for testing.

Basically all the users would have had an userid starting at either 500 on the Redhat systems or 1000 on the Ubunutu systems. I was using the > 1000 to get rid of all the user accounts that are system accounts and such in /etc/passwd.

If there was a directory /home/root and there was not a user with a userid of root > 1000 then yes I would want to delete it.

Even if that means it belongs to root, uid 0, and removing that dir would prevent the administrator from logging in ever again? Some FTP daemons have a /home/ftp, and a UID less than 1000, that'd vanish too with unknown results.

I think you need to rethink your criteria.

I am starting to see your point. So I guess I should change it to I would like to remove all user directories in /home/ that have a uid > 1000 and are not also in /etc/passwd

So logically my code would go something like

if uid of folder in /home/ > 1000 and not a uid in /etc/passwd
    delete folder
Then loop for every folder in /home/

Looking in find's options, I see this useful thing:

 %u     File's user name, or numeric user ID if the user has no name.

So find itself can tell you when a user's been deleted! Lovely.

So you can do this:

find /home -type d -mindepth 1 -maxdepth 1 -printf '%u %f\n' |
        # Print only pure numbers > 1000
        awk '$1 ~ /^[0-9]*$/ && $1 > 1000' |
        while read UID DIR
        do
                echo "/home/${DIR} has uid ${UID} and no username:"
                ls -ld "/home/${DIR}"
        done