How to Add and Delete Users from the Command Line

Terminal showing commands to add and delete Linux users: useradd, deluser, userdel, passwd, sudo examples, sample output and notes on home creation and group setup with sudo tips..

How to Add and Delete Users from the Command Line
SPONSORED

Sponsor message — This article is made possible by Dargslan.com, a publisher of practical, no-fluff IT & developer workbooks.

Why Dargslan.com?

If you prefer doing over endless theory, Dargslan’s titles are built for you. Every workbook focuses on skills you can apply the same day—server hardening, Linux one-liners, PowerShell for admins, Python automation, cloud basics, and more.


How to Add and Delete Users from the Command Line

Managing user accounts through the command line represents one of the most fundamental skills for system administrators, developers, and IT professionals working with Linux and Unix-based systems. Whether you're configuring a new server, maintaining security protocols, or automating user provisioning processes, understanding how to efficiently create and remove user accounts directly from the terminal is essential for maintaining system integrity and operational efficiency. The command line interface provides unparalleled control, speed, and scriptability compared to graphical user interface alternatives, making it the preferred method for professionals managing multiple systems or implementing automated workflows.

User account management encompasses the entire lifecycle of creating, modifying, and removing user profiles within an operating system environment. This process involves not only the basic creation or deletion of accounts but also the configuration of home directories, shell environments, group memberships, password policies, and access permissions. Throughout this comprehensive guide, we'll explore multiple approaches to user management, examining both traditional and modern methods, discussing security considerations, and providing practical examples that reflect real-world scenarios encountered in production environments.

By the end of this guide, you'll gain practical knowledge of essential commands like useradd, userdel, adduser, and deluser, understand the differences between various Linux distributions' approaches to user management, learn how to handle edge cases and potential complications, and develop the confidence to implement secure user management practices in your own systems. We'll cover everything from basic single-user operations to batch processing techniques, security best practices, and troubleshooting common issues that arise during user account administration.

Understanding User Account Fundamentals

Before diving into specific commands and techniques, it's crucial to understand the underlying architecture of user accounts in Linux and Unix systems. Every user account consists of several interconnected components stored across multiple system files. The primary user database resides in /etc/passwd, which contains basic account information including username, user ID (UID), primary group ID (GID), home directory path, and default shell. Despite its name, this file no longer stores actual passwords, which have been moved to the more secure /etc/shadow file for enhanced security.

The shadow file contains encrypted password hashes along with password aging information, expiration dates, and account status flags. This separation allows the passwd file to remain world-readable for legitimate system functions while keeping sensitive authentication data protected with restrictive permissions. Group information is similarly split between /etc/group, which lists group names and members, and /etc/gshadow, which stores group passwords and administrative data.

"Understanding the relationship between passwd, shadow, and group files is fundamental to preventing configuration errors that could compromise system security or cause authentication failures."

When you create a user account, the system assigns a unique numeric identifier called a UID. Conventional Linux systems reserve UIDs below 1000 for system accounts and services, while regular user accounts typically start at 1000 or 1001. This distinction helps administrators quickly identify account types and apply appropriate security policies. Similarly, each user belongs to at least one group identified by a GID, with the ability to be a member of multiple supplementary groups for granular access control.

Essential Commands for Adding Users

Linux distributions provide multiple commands for creating user accounts, each with distinct characteristics and use cases. The two primary tools are useradd and adduser, though their behavior varies significantly across different distributions. Understanding these differences is critical for writing portable scripts and avoiding unexpected behavior when working across heterogeneous environments.

Using the useradd Command

The useradd command represents the low-level, system-native utility for creating user accounts. Available on virtually all Linux distributions, it provides direct access to user creation functionality with minimal abstraction. This command requires explicit specification of most parameters, making it ideal for scripting and automation where precise control is necessary. The basic syntax follows this pattern:

sudo useradd [options] username

A basic user creation operation might look like this:

sudo useradd -m -s /bin/bash -c "John Developer" jdeveloper

This command creates a user named "jdeveloper" with a home directory (-m flag), sets the default shell to bash (-s flag), and adds a comment field typically used for the full name (-c flag). However, this basic invocation doesn't set a password, leaving the account in a locked state until you explicitly configure authentication credentials using the passwd command:

sudo passwd jdeveloper

The useradd command offers extensive options for customizing user account creation:

  • 🔹 -d /custom/path - Specifies a custom home directory location instead of the default /home/username
  • 🔹 -g groupname - Sets the primary group for the user
  • 🔹 -G group1,group2 - Adds the user to supplementary groups
  • 🔹 -u 1500 - Explicitly sets the UID instead of using the next available number
  • 🔹 -e 2024-12-31 - Sets an account expiration date in YYYY-MM-DD format

For system service accounts that don't require login capabilities, you can create restricted accounts using additional flags:

sudo useradd -r -s /usr/sbin/nologin -d /var/lib/servicename servicename

The -r flag creates a system account with a UID below the normal user range, while -s /usr/sbin/nologin prevents interactive login attempts, enhancing security for service accounts that should never be accessed directly by users.

Working with the adduser Command

The adduser command provides a higher-level, more user-friendly interface for account creation, particularly on Debian-based distributions like Ubuntu. Rather than requiring explicit specification of every parameter, adduser presents an interactive wizard that guides you through the account creation process, automatically handling common configurations based on system defaults defined in /etc/adduser.conf.

sudo adduser newusername

This simple command launches an interactive session that prompts for password creation and optional user information fields like full name, room number, work phone, and home phone. The command automatically creates the home directory, copies skeleton files from /etc/skel, and configures appropriate permissions without requiring additional flags.

"The adduser command's interactive nature makes it ideal for manual account creation, while useradd's explicit parameter requirements make it better suited for scripting and automation scenarios."

On Red Hat-based distributions like CentOS, Rocky Linux, and Fedora, adduser typically functions as a symbolic link to useradd, meaning both commands exhibit identical behavior. Always verify your distribution's implementation before writing scripts that depend on specific command behavior.

Comprehensive User Deletion Techniques

Removing user accounts requires careful consideration of data retention policies, security implications, and potential impact on system services or file ownership. The primary commands for user deletion are userdel and deluser, each offering different approaches to account removal with varying levels of thoroughness.

Basic User Deletion with userdel

The userdel command provides the fundamental user removal functionality across all Linux distributions. In its simplest form, it removes the user's entry from system authentication files while leaving the home directory and mail spool intact:

sudo userdel username

This conservative approach preserves user data, which can be valuable for audit purposes, data recovery, or transfer to another user. However, it creates orphaned files owned by a numeric UID that no longer corresponds to a valid username, potentially causing confusion during file system maintenance.

For complete account removal including all associated data, use the -r flag:

sudo userdel -r username

This command removes the user's home directory, mail spool, and all files within the home directory tree. However, it doesn't remove files owned by the user elsewhere in the file system, which remain associated with the deleted user's numeric UID.

The -f flag forces deletion even when the user is currently logged in:

sudo userdel -f -r username
"Forcing user deletion while they're logged in can cause system instability and should only be used in emergency situations where immediate account removal is necessary for security reasons."

Advanced Deletion with deluser

On Debian-based systems, the deluser command offers additional convenience features and safety checks. The basic syntax mirrors userdel:

sudo deluser username

To remove the home directory and mail spool:

sudo deluser --remove-home username

The deluser command provides extra options for thorough cleanup:

sudo deluser --remove-all-files username

This powerful option removes all files owned by the user across the entire file system, not just within the home directory. Use this with extreme caution, as it can inadvertently delete important system files if the user account had administrative privileges or owned service-related files.

Command Options and Parameters Reference

Command Option Description Example
useradd -m Creates home directory if it doesn't exist useradd -m username
useradd -s Specifies the login shell useradd -s /bin/zsh username
useradd -d Sets custom home directory path useradd -d /custom/home username
useradd -g Assigns primary group useradd -g developers username
useradd -G Adds to supplementary groups useradd -G sudo,docker username
useradd -u Explicitly sets UID useradd -u 1500 username
useradd -r Creates system account useradd -r serviceaccount
useradd -e Sets account expiration date useradd -e 2024-12-31 username
userdel -r Removes home directory and mail spool userdel -r username
userdel -f Forces deletion even if user is logged in userdel -f username
deluser --remove-home Deletes home directory deluser --remove-home username
deluser --remove-all-files Removes all files owned by user system-wide deluser --remove-all-files username

Security Considerations and Best Practices

Implementing proper security measures during user account management is paramount for maintaining system integrity and preventing unauthorized access. Every account creation or deletion operation carries potential security implications that extend beyond the immediate action.

Password Policy Implementation

When creating new user accounts, immediately establishing strong password policies prevents security vulnerabilities. Rather than allowing users to set their own initial passwords, consider generating secure random passwords and distributing them through secure channels:

sudo useradd -m username
sudo passwd username
# Enter a strong, randomly generated password

For enhanced security, force password changes on first login:

sudo chage -d 0 username

This command sets the password change date to epoch zero, triggering a mandatory password reset on the user's next login attempt. Configure password aging policies to enforce regular password rotations:

sudo chage -M 90 -m 7 -W 14 username

This configuration requires password changes every 90 days (-M), prevents changes within 7 days of the last change (-m), and warns users 14 days before expiration (-W).

Principle of Least Privilege

When assigning group memberships and permissions, adhere strictly to the principle of least privilege. Grant users only the minimum access necessary for their specific roles and responsibilities. Avoid adding users to administrative groups like sudo or wheel unless absolutely required:

sudo useradd -m -G developers,docker username
"Excessive privileges granted during account creation often remain long after they're needed, creating unnecessary security exposure that attackers can exploit through compromised accounts."

Regularly audit user group memberships and remove unnecessary privileges:

groups username
sudo gpasswd -d username unnecessarygroup

Account Lifecycle Management

Implement systematic processes for managing the complete user account lifecycle from creation through deletion. When employees leave an organization or change roles, disable accounts immediately rather than deleting them:

sudo usermod -L username
sudo usermod -s /usr/sbin/nologin username

The -L flag locks the password, preventing authentication, while changing the shell to nologin prevents any interactive access. This approach preserves audit trails and file ownership while preventing unauthorized access. After an appropriate retention period, permanently delete the account following your organization's data retention policies.

Handling Files and Ownership After User Deletion

One of the most overlooked aspects of user deletion involves managing files that remain after account removal. When you delete a user without the -r flag or when files exist outside the home directory, these files become orphaned, owned by a numeric UID that no longer corresponds to a valid username.

Before deleting a user, identify all files they own across the system:

sudo find / -user username -ls 2>/dev/null

This command searches the entire file system for files owned by the specified user, redirecting error messages to /dev/null to suppress permission denied warnings. Review this list carefully to identify files that should be preserved, reassigned, or deleted.

To reassign ownership of all files to another user before deletion:

sudo find / -user oldusername -exec chown newusername:newgroup {} \; 2>/dev/null

For files that should be archived rather than reassigned, create a backup before deletion:

sudo tar czf /backup/username-files-$(date +%Y%m%d).tar.gz $(sudo find / -user username 2>/dev/null)
"Orphaned files can cause significant confusion during system maintenance and may indicate incomplete user removal processes that could have security implications."

After user deletion, locate orphaned files by searching for the numeric UID:

sudo find / -uid 1001 -ls 2>/dev/null

Replace 1001 with the UID of the deleted user. These files should be evaluated individually to determine appropriate disposition based on content, importance, and organizational policies.

Batch User Management and Automation

In enterprise environments managing dozens or hundreds of user accounts, manual individual account creation becomes impractical. Batch processing techniques and automation scripts dramatically improve efficiency while reducing human error.

Creating Multiple Users from a List

Prepare a text file containing usernames, one per line, then process it with a shell script:

#!/bin/bash
while IFS= read -r username; do
    sudo useradd -m -s /bin/bash "$username"
    echo "$username:TemporaryPassword123!" | sudo chpasswd
    sudo chage -d 0 "$username"
    echo "Created user: $username"
done < userlist.txt

This script reads usernames from userlist.txt, creates each account with a home directory and bash shell, sets a temporary password, and forces a password change on first login. For production use, replace the hardcoded password with a secure random generation function.

CSV-Based User Provisioning

For more complex scenarios requiring different configurations per user, use a CSV file containing multiple fields:

username,fullname,groups,shell
jdoe,John Doe,developers,/bin/bash
asmith,Alice Smith,"developers,docker",/bin/zsh
bwilson,Bob Wilson,operations,/bin/bash

Process this file with a more sophisticated script:

#!/bin/bash
while IFS=, read -r username fullname groups shell; do
    # Skip header line
    [[ "$username" == "username" ]] && continue
    
    sudo useradd -m -c "$fullname" -s "$shell" "$username"
    
    if [[ -n "$groups" ]]; then
        sudo usermod -aG "$groups" "$username"
    fi
    
    # Generate random password
    password=$(openssl rand -base64 12)
    echo "$username:$password" | sudo chpasswd
    sudo chage -d 0 "$username"
    
    echo "Created: $username | Password: $password"
done < users.csv
"Automated user provisioning scripts should always log actions and generated passwords to secure locations for audit purposes and password distribution to new users."

Bulk User Deletion

Similarly, remove multiple users efficiently with batch processing:

#!/bin/bash
while IFS= read -r username; do
    if id "$username" &>/dev/null; then
        sudo userdel -r "$username"
        echo "Deleted user: $username"
    else
        echo "User not found: $username"
    fi
done < deletion_list.txt

This script includes error checking to verify user existence before attempting deletion, preventing script failures and providing clear feedback about each operation's status.

Distribution-Specific Considerations

Distribution Family Primary Command Key Characteristics Configuration Files
Debian/Ubuntu adduser/deluser Interactive, user-friendly, extensive defaults /etc/adduser.conf, /etc/deluser.conf
Red Hat/CentOS/Fedora useradd/userdel Low-level, requires explicit parameters /etc/default/useradd, /etc/login.defs
Arch Linux useradd/userdel Minimal defaults, maximum flexibility /etc/default/useradd, /etc/login.defs
SUSE/openSUSE useradd/userdel YaST integration available for GUI management /etc/default/useradd, /etc/login.defs

Troubleshooting Common Issues

Despite following best practices, user management operations occasionally encounter problems. Understanding common issues and their solutions helps maintain smooth system administration workflows.

Username Already Exists

Attempting to create a user that already exists produces an error. Before creating accounts, verify the username is available:

id username 2>/dev/null && echo "User exists" || echo "User available"

If you need to recreate a user with the same name, first delete the existing account or choose a different username.

Home Directory Already Exists

When a home directory remains after user deletion and you attempt to recreate the user, conflicts arise. Remove the orphaned directory first:

sudo rm -rf /home/username
sudo useradd -m username

Alternatively, use the existing directory without the -m flag, though this requires manually correcting ownership and permissions:

sudo useradd -d /home/username username
sudo chown -R username:username /home/username

UID or GID Conflicts

When explicitly specifying UIDs, conflicts occur if that UID is already assigned. Check existing UIDs:

getent passwd | cut -d: -f3 | sort -n

Choose an unused UID or omit the -u flag to allow automatic assignment. Similar issues affect GID specifications, resolved by checking /etc/group or using getent group.

Permission Denied Errors

User management commands require root privileges. Always use sudo or execute commands as root. If sudo access fails, verify your user belongs to the appropriate administrative group:

groups
sudo usermod -aG sudo $USER  # Debian/Ubuntu
sudo usermod -aG wheel $USER  # Red Hat/CentOS

After adding yourself to an administrative group, log out and back in for changes to take effect.

User Currently Logged In

Deleting users who are currently logged in can cause system instability. Check active sessions before deletion:

who | grep username
ps -u username

Terminate user sessions gracefully:

sudo pkill -u username
sudo userdel -r username

For persistent login sessions, use the -f flag with userdel, though this should be reserved for emergency situations.

"Always verify users are logged out before attempting account deletion to prevent data corruption and system instability caused by active processes losing their associated user context."

Advanced User Management Techniques

Configuring User Environments

The /etc/skel directory contains template files automatically copied to new users' home directories. Customize this directory to provide standard configurations:

sudo nano /etc/skel/.bashrc
sudo nano /etc/skel/.bash_profile
sudo mkdir /etc/skel/.config

Any files or directories placed in /etc/skel are automatically replicated to new user home directories during account creation, ensuring consistent environments across all users.

Implementing Account Expiration

For temporary accounts like contractors or interns, set automatic expiration dates:

sudo useradd -m -e 2024-12-31 contractor
sudo chage -E 2024-12-31 existinguser

The system automatically disables these accounts after the specified date, reducing security risks from forgotten temporary accounts. Monitor upcoming expirations:

sudo chage -l username

Managing Service Accounts

Service accounts require special handling to prevent interactive login while allowing service operation:

sudo useradd -r -s /usr/sbin/nologin -d /var/lib/servicename -M servicename

The -r flag creates a system account, -s sets a non-interactive shell, -d specifies a service-specific directory, and -M prevents home directory creation. Configure appropriate file ownership for service directories:

sudo mkdir -p /var/lib/servicename
sudo chown servicename:servicename /var/lib/servicename
sudo chmod 750 /var/lib/servicename

Auditing and Monitoring User Accounts

Regular auditing of user accounts helps identify security issues, unused accounts, and configuration problems. Generate a comprehensive user list:

getent passwd | awk -F: '$3 >= 1000 {print $1, $3, $7}'

This command displays regular user accounts (UID ≥ 1000) with their UIDs and shells. Identify accounts that haven't been used recently:

sudo lastlog | grep -v "Never"

Accounts showing "Never logged in" or very old last login dates may be candidates for removal or investigation. Check for accounts without passwords:

sudo awk -F: '($2 == "" || $2 == "!") {print $1}' /etc/shadow

These accounts represent security risks if they allow access through alternative authentication methods. Verify proper group memberships, especially for administrative groups:

getent group sudo
getent group wheel
getent group docker
"Regular user account audits should be scheduled monthly or quarterly, with immediate investigation of any anomalies like unexpected administrative privileges or recently created unknown accounts."

Integration with Configuration Management Tools

Modern infrastructure management increasingly relies on configuration management platforms like Ansible, Puppet, or Chef to maintain consistent user configurations across multiple systems. These tools provide declarative approaches to user management that ensure desired state regardless of current configuration.

Ansible User Management Example

- name: Create development team users
  user:
    name: "{{ item.username }}"
    comment: "{{ item.fullname }}"
    groups: "{{ item.groups }}"
    shell: /bin/bash
    state: present
  loop:
    - { username: 'jdoe', fullname: 'John Doe', groups: 'developers,docker' }
    - { username: 'asmith', fullname: 'Alice Smith', groups: 'developers' }

This Ansible playbook creates multiple users with specified configurations, automatically handling idempotency to prevent errors when rerun on systems where users already exist.

Puppet User Management Example

user { 'jdoe':
  ensure     => present,
  comment    => 'John Doe',
  home       => '/home/jdoe',
  shell      => '/bin/bash',
  groups     => ['developers', 'docker'],
  managehome => true,
}

Configuration management tools provide centralized control, version tracking, and audit trails for user management operations across entire infrastructure fleets.

Compliance and Regulatory Considerations

Organizations subject to regulatory frameworks like SOX, HIPAA, PCI-DSS, or GDPR face specific requirements for user account management. These regulations typically mandate comprehensive audit trails, regular access reviews, and documented processes for account lifecycle management.

Implement logging for all user management operations:

sudo auditctl -w /etc/passwd -p wa -k user_modification
sudo auditctl -w /etc/shadow -p wa -k user_modification
sudo auditctl -w /etc/group -p wa -k group_modification

These audit rules generate detailed logs whenever authentication files are modified, creating a permanent record of all user management activities. Review audit logs regularly:

sudo ausearch -k user_modification -ts recent

Document standard operating procedures for user provisioning and deprovisioning, including approval workflows, notification requirements, and data handling procedures. Maintain records of when accounts were created, modified, and deleted, along with justifications for each action.

Frequently Asked Questions

What's the difference between useradd and adduser commands?

The useradd command is a low-level system utility available on all Linux distributions that requires explicit specification of parameters like home directory creation, shell selection, and group assignments. The adduser command, primarily found on Debian-based systems, provides a higher-level interactive interface that automatically handles common configurations based on system defaults. On Red Hat-based distributions, adduser typically functions as a symbolic link to useradd, making them identical. For scripting and automation, useradd offers more predictable cross-distribution behavior, while adduser provides better user experience for manual account creation on systems where it's implemented as a separate tool.

How do I delete a user but keep their files for another user to access?

To preserve user files after account deletion, first use the find command to locate all files owned by the user across the system with "sudo find / -user username -ls 2>/dev/null". Review this list and decide which files should be reassigned to another user. Execute "sudo find / -user oldusername -exec chown newusername:newgroup {} \; 2>/dev/null" to reassign ownership. Alternatively, delete the user without the -r flag using "sudo userdel username", which removes the account but leaves the home directory and all files intact. These files will be owned by the numeric UID of the deleted user, allowing you to reassign ownership selectively later. For important data, create backups before any deletion operations.

Can I recover a deleted user account?

User account recovery depends on how the deletion was performed. If you used "userdel username" without the -r flag, the home directory and files remain intact, allowing you to recreate the account with the same username and manually restore permissions. However, if you used "userdel -r username", the home directory was permanently deleted and cannot be recovered without backups. Password hashes stored in /etc/shadow are also irretrievably lost after deletion. To prepare for potential recovery needs, always backup critical user data before deletion, maintain regular system backups, and consider disabling accounts temporarily with "usermod -L username" rather than immediate deletion, allowing a grace period for verification that the account is truly no longer needed.

Why does my newly created user account not have sudo privileges?

New user accounts are created without administrative privileges by default as a security measure following the principle of least privilege. To grant sudo access, add the user to the appropriate administrative group using "sudo usermod -aG sudo username" on Debian/Ubuntu systems or "sudo usermod -aG wheel username" on Red Hat/CentOS systems. After adding the user to the administrative group, they must log out and back in for the changes to take effect. Alternatively, configure user-specific sudo permissions by editing the sudoers file with "sudo visudo" and adding a line like "username ALL=(ALL:ALL) ALL" for full sudo access or more restrictive rules for limited administrative capabilities. Never edit /etc/sudoers directly without using visudo, as syntax errors can lock you out of administrative access.

How do I create a user account that expires automatically after a specific date?

Set automatic account expiration during user creation with the -e flag: "sudo useradd -m -e 2024-12-31 username", replacing the date with your desired expiration in YYYY-MM-DD format. For existing accounts, use the chage command: "sudo chage -E 2024-12-31 username". The system automatically disables the account after the specified date, preventing login attempts. View current expiration settings with "sudo chage -l username" to display detailed account aging information including expiration date, last password change, and password aging policies. This feature is particularly valuable for temporary contractors, interns, or project-based accounts where access should automatically terminate after a predetermined period. Set up monitoring to alert administrators before accounts expire if extensions might be needed, preventing unexpected access loss for users whose contracts are extended.