How Userdel Works In Linux

Updated: Sep 30

Userdel command can be used to delete a user and related files in Linux. In most Linux distributions, the user home and mail spool directories are not removed when removing a user account with userdel.


We are going through the whole process to see what happens after we run userdel command.



Understanding Userdel Command

The following two steps will happen for userdel command.

  1. deletes the group with the same name as the user if USERGROUPS_ENAB is set to yes in this file /etc/login.defs file. It happens only if no other user is a member of this group. If this group belongs to a shared primary user group, it will not be deleted.

  2. removes the user entries from the /etc/passwd and /etc/shadow files

  3. remove related files based on the options we put in the command


In most Linux distributions, the user home and mail spool directories are not removed when removing a user account with userdel. If we are sure to remove these files, we can use -r option (--remove).


Userdel -r Option

 -r, --remove
 Files in the user's home directory will be removed along with the home directory itself and the user's mail spool. Files located in other file systems will have to be searched for and deleted manually.

These files under other file systems are not deleted automatically. We need to remove these files separately. If the user is still login the system, userdel command will fail. We need to logout this user first.




Userdel Risky -f option

There is one risky option -f for this command. We should be very careful when we run it.

-f, --force
Remove the user even if they are currently logged in. Remove home directory and mail spool even if they are used by another user. Remove group too, if USERGROUPS_ENAB is set to yes in /etc/login.defs.

Example of Userdel command

When no option is passed in userdel command in Linux, it will delete the user from the server.

# userdel howtouselinux


Remove Linux user account including home directory and mail spool

# userdel -f howtouselinux


To remove any SELinux user mapping for the user pass the -Z option

# userdel -Z -r -f howtouselinux


Where,

  • -f : Delete Linux user account with force removal of files

  • -r : Remove Linux user account including home directory and mail spool

  • -Z : Remove any SELinux user mapping for the user when deleting user from Linux


Related Post:

Basic Linux Commands: Linux User Management

How useradd works in Linux

Linux Command: Change User Login Shell Safely

How to fix "WARNING: Your password has expired." in Linux?



165 views