Website Vidya
SecurityStep-by-Step Guide

How to Remove a User in Linux with the userdel Command

Learn remove a user in linux with syntax, essential flags, practical terminal examples, real-world sysadmin workflows, security tips, and troubleshooting.

RR
Rajesh RayLead Systems Educator
Published:
12 min read
PDF Cheat Sheet
How to Remove a User in Linux with the userdel Command
AI Executive SummaryWebsiteVidya AI

12 min read

Learn remove a user in linux with syntax, essential flags, practical terminal examples, real-world sysadmin workflows, security tips, and troubleshooting.

Key Highlights
  • What userdel Does and When to Use It
  • Availability and Installation Across Linux Distributions
  • Command Syntax, Arguments, and Exit Status Codes
Grounded in full engineering runbookWebsiteVidya AI Engine

Knowing how to properly remove a user in Linux is a critical security procedure whenever an engineer leaves an organization, a contractor engagement ends, or a temporary service account is decommissioned. Simply deleting a username entry from /etc/passwd without cleaning up associated files, crontabs, running processes, and SSH keys can leave dangerous security gaps—including orphaned files that a future user assigned the same numeric UID could accidentally inherit.

The standard cross-distribution tool for deleting user accounts is userdel, part of the shadow-utils package. By default, running sudo userdel username without flags removes the account records from /etc/passwd, /etc/shadow, /etc/group, and /etc/gshadow, while intentionally leaving /home/username intact on disk so administrators can archive or transfer critical work files first. Passing -r (--remove) instructs userdel to also delete the user's home directory and /var/mail/username spool.

In production environments, safe account offboarding follows a deliberate multi-step sequence: lock the account to block new logins, archive the home directory and crontab for compliance retention, terminate all running processes owned by the user, hunt down orphaned files outside /home, and finally execute sudo userdel -r username.

Advertisement
How to Remove a User in Linux with the userdel Command — syntax, flags, and practical terminal workflow diagram
How to Remove a User in Linux with the userdel Command — command syntax, key options, and production workflow reference.

What userdel Does and When to Use It

When userdel runs, it first locks the system authentication databases (/etc/.pwd.lock) and verifies whether any running process in the /proc filesystem currently carries the target user's real UID. Unless the -f (--force) flag is supplied, userdel refuses to delete an account that has active processes (returning exit code 8) to prevent running tasks from suddenly operating under an unmapped numeric UID.

Once the pre-flight check passes, userdel strips the target account line from /etc/passwd and /etc/shadow, removes the username from all supplementary group member lists in /etc/group and /etc/gshadow, and—if USERGROUPS_ENAB yes is configured in /etc/login.defs and no other user shares the primary group—automatically deletes the user's empty user-private group (UPG). If -r is specified, userdel recursively unlinks the directory path recorded in the sixth field of /etc/passwd.

Linux enforces discretionary access control (DAC) by evaluating the effective User ID (EUID), effective Group ID (EGID), and supplementary groups against inode permission bits. When userdel executes, the Virtual File System (VFS) and active Linux Security Modules (SELinux or AppArmor) validate the caller's privileges before committing changes to disk or account databases.

Availability and Installation Across Linux Distributions

The userdel utility is packaged in shadow-utils / passwd across mainstream Linux distributions. It is pre-installed on standard Ubuntu, Debian, RHEL, Rocky Linux, AlmaLinux, Fedora, and Arch Linux systems, while minimal container images may require manual installation:

Advertisement

Before running administrative tasks or automation scripts, verify whether userdel is installed and inspect which binary path and version your shell resolves:

type -a userdel
userdel --version 2>/dev/null || man -f userdel

# Illustrative output (reviewed against documentation)
userdel is /usr/bin/userdel
userdel (shadow-utils / passwd)
# Debian / Ubuntu
sudo apt-get update && sudo apt-get install -y passwd

# RHEL / Rocky / AlmaLinux / Fedora
sudo dnf install -y shadow-utils

# Arch Linux
sudo pacman -S --noconfirm shadow

# Alpine Linux
sudo apk add --no-cache shadow

Command Syntax, Arguments, and Exit Status Codes

userdel [OPTIONS] USERNAME

The syntax userdel [OPTIONS] USERNAME requires a single existing username operand and must be executed with root privileges (sudo). Because userdel reads the target user's home directory path from /etc/passwd at the moment of deletion, you must pass -r during the initial userdel call if you want automatic cleanup; once the /etc/passwd line is gone, userdel can no longer look up where the user's home directory was located.

On Debian and Ubuntu systems, administrators also have access to the Perl wrapper deluser (for example, sudo deluser --remove-home --backup-to /var/backups username), which provides a convenient built-in --backup flag. However, userdel is universal across Debian, Ubuntu, RHEL, Rocky Linux, Fedora, SUSE, and Arch Linux.

  • 0 — User account (and home directory if -r was passed) successfully removed.
  • 1 — Cannot update /etc/passwd or /etc/shadow (lock file conflict or read-only filesystem).
  • 2 — Invalid command syntax or unknown option.
  • 6 — The specified user account does not exist in /etc/passwd.
  • 8 — The user is currently logged in or has running processes on the system.
  • 10 — Cannot update /etc/group or /etc/gshadow.
  • 12 — Account entry was deleted from /etc/passwd, but userdel could not remove the home directory or mail spool.

Important Options and Flags Reference

Option / FlagLong Form / ArgumentTechnical Behavior and Purpose
-r--removeRemove the user's home directory and mail spool (/var/mail/USERNAME) along with the account entry.
-f--forceForce removal of the user account and files even if the user is still logged in or the home directory is shared.
-Z--selinux-userRemove any SELinux user mapping associated with the user's login account.
-R--root CHROOT_DIRApply changes inside the specified chroot directory and use its /etc configuration files.
-P--prefix PREFIX_DIRApply account deletions within the specified prefix directory tree without chrooting.
--help-hDisplay help message and exit.
--remove-homedeluser (Debian)Equivalent flag when using the Debian/Ubuntu deluser wrapper instead of userdel -r.

Always prefer sudo userdel -r username over bare sudo userdel username once you have backed up any required files. Leaving /home/username behind on disk after deleting the account causes ls -l /home to display raw numeric UIDs (such as 1001). Worse, when useradd is later executed to create a new employee account, shadow-utils may allocate the lowest unused UID (1001), automatically granting the new user full ownership of the previous employee's leftover files and .ssh keys!

Advertisement

Use the -f (--force) option with extreme caution. Rather than forcing userdel -rf while a user has active processes—which leaves orphan processes running under an unmapped UID—explicitly terminate all user sessions first using sudo loginctl terminate-user username or sudo pkill -9 -u username, and then run sudo userdel -r username cleanly.

When combining short flags on the command line, POSIX and GNU utilities allow clustering boolean flags behind a single hyphen, provided any option taking an argument appears last. In automated shell scripts, using long-form GNU options where portable makes self-documenting code that is easier to audit during peer review.

Practical Basic and Advanced Usage Examples

1. Remove a User Account and Delete Their Home Directory (-r)

Use -r to completely remove a user account from /etc/passwd, /etc/shadow, and /etc/group while deleting /home/username and /var/mail/username.

sudo userdel -r auditor01
getent passwd auditor01 || echo "Account auditor01 completely removed"

# Illustrative output (reviewed against documentation)
userdel: auditor01 mail spool (/var/mail/auditor01) not found
Account auditor01 completely removed

The informational message mail spool not found is completely normal on modern servers where local mail delivery is not used; userdel still removes the /etc/passwd record and /home/auditor01 with exit status 0.

2. Remove a User Account While Keeping Their Home Directory

If a developer leaves the team and you want to revoke their login immediately while keeping /home/dev_liam intact for code handoff, omit -r.

sudo userdel dev_liam
ls -ld /home/dev_liam

# Illustrative output (reviewed against documentation)
drwxr-x--- 4 1004 1004 4096 Oct 22 15:20 /home/dev_liam

Because the account dev_liam (UID 1004) was removed from /etc/passwd and /etc/group, ls -ld now displays the raw numeric UID and GID (1004) stored in the directory inode. Reassign ownership (sudo chown -R manager:manager /home/dev_liam) promptly so UID 1004 is not reused.

3. Stop Active User Sessions Before Deleting the Account

If a user has an active SSH session, tmux server, or background process, userdel will exit with code 8 (user is currently used by process). Terminate their systemd user slice first.

sudo loginctl terminate-user alex
sudo pkill -9 -u alex || true
sudo userdel -r alex

loginctl terminate-user stops the user's [email protected] systemd manager and all child cgroup processes cleanly, allowing userdel -r to succeed without forcing.

4. Remove User Cron Jobs and Pending at Jobs Before Deletion

userdel -r deletes the home directory and mail spool, but does NOT automatically purge personal crontabs in /var/spool/cron/crontabs. Always remove scheduled jobs before deleting the user.

sudo crontab -r -u dev_maya 2>/dev/null || echo "No crontab for dev_maya"
sudo userdel -r dev_maya

# Illustrative output (reviewed against documentation)
No crontab for dev_maya

Running crontab -r -u USERNAME ensures no orphaned scheduled tasks attempt to execute under a deleted account.

5. Find and Reassign Orphaned Files Left Outside /home

Users frequently create files in /tmp, /var/tmp, /opt, or /srv that userdel -r does not touch. Use find -nouser (or -uid) to locate and clean them up.

sudo find /tmp /var/tmp /srv -xdev \( -nouser -o -nogroup \) -ls

# Illustrative output (reviewed against documentation)
262199      4 -rw-r--r--   1 1001     1001          512 Oct 22 12:10 /tmp/deploy_notes.txt

The -nouser and -nogroup predicates in find match any file whose numeric UID or GID has no corresponding entry in /etc/passwd or /etc/group.

6. Archive a User's Home Directory Before Deleting on Any Distro

Create a compressed, timestamped tarball of the user's home directory in /var/backups before running userdel -r.

sudo mkdir -p /var/backups/offboarded-users
sudo tar -czf /var/backups/offboarded-users/priya-$(date +%F).tar.gz -C /home priya
sudo chmod 0600 /var/backups/offboarded-users/priya-*.tar.gz
sudo userdel -r priya
ls -lh /var/backups/offboarded-users/

# Illustrative output (reviewed against documentation)
total 4.0K
-rw------- 1 root root 1.8K Oct 22 15:40 priya-2026-10-22.tar.gz

Archiving /home/priya into a 0600 root-owned tarball preserves audit logs and work artifacts while allowing userdel -r to reclaim the active UID and home directory cleanly.

Real-World Workflows, Pipelines, and Shell Automation

Complete Production User Offboarding Workflow Script

When revoking employee access on production Linux hosts, this comprehensive script locks the account immediately, archives the home directory, removes cron jobs, terminates all active processes, purges /etc/sudoers.d/ drop-ins, and deletes the user.

#!/usr/bin/env bash
set -euo pipefail

TARGET_USER="${1:?Usage: $0 USERNAME}"
BACKUP_DIR="/var/backups/offboarded"

if ! id "$TARGET_USER" >/dev/null 2>&1; then
  echo "Error: User $TARGET_USER does not exist." >&2
  exit 1
fi

echo "[1/6] Locking account $TARGET_USER..."
sudo usermod -L -e 1 "$TARGET_USER"

echo "[2/6] Terminating active sessions and processes..."
sudo loginctl terminate-user "$TARGET_USER" 2>/dev/null || true
sudo pkill -9 -u "$TARGET_USER" 2>/dev/null || true

echo "[3/6] Removing user crontabs..."
sudo crontab -r -u "$TARGET_USER" 2>/dev/null || true

echo "[4/6] Backing up home directory to $BACKUP_DIR..."
USER_HOME="$(getent passwd "$TARGET_USER" | cut -d: -f6)"
if [ -d "$USER_HOME" ]; then
  sudo install -d -m 0700 "$BACKUP_DIR"
  sudo tar -czf "$BACKUP_DIR/${TARGET_USER}-$(date +%F).tar.gz" "$USER_HOME" 2>/dev/null
fi

echo "[5/6] Removing custom sudoers drop-in if present..."
sudo rm -f "/etc/sudoers.d/$TARGET_USER"

echo "[6/6] Deleting user and home directory..."
sudo userdel -r "$TARGET_USER"
echo "Successfully offboarded $TARGET_USER."

# Illustrative output (reviewed against documentation)
[1/6] Locking account ops_noah...
[2/6] Terminating active sessions and processes...
[3/6] Removing user crontabs...
[4/6] Backing up home directory to /var/backups/offboarded...
[5/6] Removing custom sudoers drop-in if present...
[6/6] Deleting user and home directory...
Successfully offboarded ops_noah.

Notice step 5 (sudo rm -f /etc/sudoers.d/$TARGET_USER): userdel never modifies /etc/sudoers or /etc/sudoers.d/. Removing leftover sudoers drop-in files prevents privilege escalation if the same username is ever recreated in the future.

Audit and Reclaim Orphaned Files Across Local Filesystems

After deleting old accounts, run an automated scan across mounted local filesystems to transfer orphaned files to root:root (or delete temporary files).

sudo find /home /srv /opt /var -xdev \( -nouser -o -nogroup \) -print0 |   sudo xargs -0 -r chown -v root:root

# Illustrative output (reviewed against documentation)
changed ownership of '/srv/webapps/legacy-config.yml' from 1004:1004 to root:root

Using -print0 with xargs -0 -r handles filenames containing spaces safely and runs chown root:root only if orphaned files are actually discovered.

Pipelines, Redirection, Quoting, and Shell Expansion

When embedding userdel inside shell pipelines (|), conditional chains (&& and ||), or command substitutions ($(...)), the calling shell performs tilde expansion, variable interpolation, and globbing before invoking the binary. Always wrap paths, patterns, and variables in quotes so whitespace and wildcard characters (*, ?) are not expanded prematurely, and use set -euo pipefail in unattended scripts.

Permissions, Security Implications, and Safe Execution

Deleting a user with userdel does NOT remove any custom privilege rules referencing that username in /etc/sudoers or /etc/sudoers.d/*, nor does it revoke SSH certificates signed by an SSH Certificate Authority (CA) unless the principal or key ID is added to an OpenSSH RevokedKeys list. Always audit /etc/sudoers.d/ and centralized identity providers during offboarding.

If compliance policies require preserving audit trail attribution for historical file ownership or journald logs, consider locking the account permanently (sudo usermod -L -e 1 -s /usr/sbin/nologin username and removing ~/.ssh/authorized_keys) instead of deleting the UID from /etc/passwd. Locking blocks all authentication while preventing the numeric UID from ever being reassigned to a future user.

GNU/Linux, BSD, and BusyBox Implementation Differences

The userdel binary is standard across all Linux distributions using shadow-utils (Debian, Ubuntu, RHEL, Rocky Linux, Fedora, SUSE, Arch). Debian and Ubuntu additionally offer deluser (sudo deluser --remove-home username), which reads /etc/deluser.conf.

On Alpine Linux (BusyBox), the built-in command is deluser [--remove-home] USERNAME unless you install the shadow package (apk add shadow). On FreeBSD, use pw userdel -n username -r, and on macOS use sysadminctl -deleteUser username.

Troubleshooting Common Errors and Diagnostics

userdel: user username is currently used by process 4182

Root Cause: The target user still has at least one running process (often an active SSH session, tmux/screen server, or systemd --user instance).

Resolution: Terminate the user's systemd session slice with loginctl terminate-user and kill remaining processes with pkill -9 -u before re-running userdel -r.

sudo loginctl terminate-user username
sudo pkill -9 -u username
sudo userdel -r username

userdel: group username not removed because it has other members

Root Cause: Another user account still lists username's group as either its primary group in /etc/passwd or a supplementary group in /etc/group.

Resolution: Inspect the group membership with getent group username, reassign the other user's group if appropriate, and then delete the group with groupdel.

getent group username
sudo groupdel username

userdel: /home/username not owned by username, not removing

Root Cause: The root of /home/username is owned by root or another UID (common with SFTP chroot jails), so userdel -r refuses to delete it as a safety precaution.

Resolution: Verify the path is exclusively for that user and remove the directory manually with sudo rm -rf /home/username after userdel completes.

ls -ld /home/username
sudo rm -rf /home/username

Authoritative References and Official Documentation

Frequently Asked Questions

Quick answers to common questions and configurations

4 FAQs
Run sudo userdel -r username. The -r (--remove) flag tells userdel to delete the user's home directory (typically /home/username) and their mail spool (/var/mail/username) in addition to removing their account entries from /etc/passwd and /etc/shadow.
Many enterprise security teams first lock the account (sudo usermod -L -e 1 -s /usr/sbin/nologin username and remove ~/.ssh/authorized_keys) for 30 to 90 days so UID mappings and file ownership remain intact during handoff, then archive the home directory and run sudo userdel -r username.
When -r is passed, userdel always checks /var/mail/username (or /var/spool/mail/username) and deletes the file if present. If the user never received local system mail, that file does not exist; the message is harmless and the user and home directory are still deleted.
userdel is the low-level compiled binary included on all mainstream Linux distributions (Ubuntu, Debian, RHEL, Fedora, Arch). deluser is a Debian/Ubuntu-specific Perl wrapper around userdel that supports extra convenience options such as --backup-to.
RR
Written byVerified Author

Rajesh Ray

I’m Rajesh Rai, a full-stack developer, Linux administrator, and technology enthusiast passionate about making complex technology easier to understand and use.

SPAM-FREE MODERATED DISCOURSE

Join the Conversation & Perspective

Have thoughts, counterpoints, or reflections on this story? Engage directly with fellow readers and editorial contributors.

AT
MP
JV
+2

No comments on this guide yet. Be the first to share your thoughts or ask a question!

Recommended Reading10 Guides

Related Technical Guides

Tested runbooks, server administration walkthroughs, and troubleshooting guides

Featured Infrastructure PartnerUp to 75% OFF + 3 Months Free

Supercharge Your Linux & Cloud Workloads with Hostinger

Deploy high-speed NVMe KVM VPS, Docker containers, and LiteSpeed-accelerated WordPress servers in under 60 seconds with full root access, dedicated IPv4, and 24/7 technical support.

Pure NVMe SSD StorageFull Root Access & SSHFree Domain & Unlimited SSL99.9% Uptime SLA
Plans from$2.99/mo
Claim Hostinger DealAffiliate link • Special discount applied at checkout