arcee123 arcee123 - 9 months ago 55
Linux Question

locate home directories of deleted users in linux

I'm trying to write a bash script to locate home directories of users long since deleted, that have nothing but their profile files (.bashrc, .bash_logout, .profile, etc....) still left in.

I tried

find . -type d -empty -print

but it only finds truly empty directories with active users. I need those directories that have no users, plus I don't care about hidden files. I only care if the folders have actual user files in it.



find has an option that might come in handy in this case: -nouser. It matches with files that have a (numeric) user id that corresponds to no user as specified in /etc/passwd. So for example, the following command will print all directories under /home that are not owned by a current user:

find /home -mindepth 1 -maxdepth 1 -type d -nouser

Edit: If you only want to print the directories that have no non-hidden files, you can amend the above as follows:

find /home -mindepth 1 -maxdepth 1 -type d -nouser -print0 |
    while IFS= read -r -d '' dir; do
        (($(ls "$dir" | wc -l) == 0)) && echo $dir