Delete a user and all files owned by this user

I have used deluser without the parameter --remove-all-files:

$ deluser 'user'

Is there a way other than rm -r /home/user to remove all files owned by a user now (since I have already executed deluser)?


Solution 1:

You will have to manually find files, which probably was what deluser would do.

Please note --remove-all-files is not the same as rm -r /home/user. The latter only removes the homedir (which may include files not owned by that user, although not usual), the former removes all files owned by that user from the system. At least if the manpage is to be trusted.

GNU find has a -user test, so you can do find / -user xxx to find all files owned by user xxx. xxx would be the user name, and can (and in this case will have to, as the user no longer exists) be the user's numeric ID. find also has a -delete option, so

find / -user xxx -delete

Should do it, although I've not tested the command with all the options at the same time.

EDIT: Numeric ID: The reason why I said you have to use a numeric ID is because, as you already deleted the user, his entry in /etc/passwd was deleted (it had, along with other stuff, the user ID, along with his username).

So, if you didn't remove his homedir, one of the easiest ways is to just query for the ID of the owner of that homedir:

stat -c %u /home/user/

(stat is a tool to read filesystem data. -c %u tells stat how to write its output, here I'm asking it to simply output the user ID)

If you like one-liners, you can even chain both commands:

find / -user $(stat -c %u /home/user/) -delete

(Of course you may prefer to run it first with no -delete to make sure there's nothing you want to keep, and to catch any mistake you've made writing the rest of the command. Mistakes when doing recursive deletion operations on / are not for the faint of heart.)

Solution 2:

Another option would be to re-add the user with adduser, specifying the old UID, and then run deluser again, this time with the --remove-all-files flag.

Suppose, for instance, that the user had username alice and UID 1001:

sudo adduser --uid 1001 alice
sudo deluser --remove-all-files alice

Solution 3:

gnu find has the options -nouser and -nogroup, look it up in man find. With these options you can find all files in your filesystem(s) that have no corresponding user in /etc/passwd. If you have not created a new user with the old uids of your deleted users, this is a possibility to find these orphaned files.

However, you might find more files - not only those who belonged to your deleted one.