How to Create Users in Linux with the useradd Command
Learn create users in linux with syntax, essential flags, practical terminal examples, real-world sysadmin workflows, security tips, and troubleshooting.
13 min read
Learn create users in linux with syntax, essential flags, practical terminal examples, real-world sysadmin workflows, security tips, and troubleshooting.
- What useradd Does and When to Use It
- Availability and Installation Across Linux Distributions
- Command Syntax, Arguments, and Exit Status Codes
Knowing how to create users in Linux is a foundational skill for system administrators, DevOps engineers, and security practitioners managing multi-tenant servers, cloud virtual machines, and container images. Because Linux is inherently a multi-user operating system from the kernel up, every running process, file descriptor, and network socket is bound to a numeric User ID (UID) and Group ID (GID). Whether you are onboarding a new software engineer, isolating a database daemon inside an unprivileged service account, or writing automated cloud-init provisioning scripts, useradd provides deterministic, non-interactive control over user creation.
To create users in Linux from the command line, run sudo useradd -m -s /bin/bash username to provision the account with a dedicated home directory and an interactive login shell, followed by sudo passwd username to set an authentication password. The useradd utility is the standard, low-level POSIX account creation binary available across all major Linux distributions.
While Debian and Ubuntu systems also include a friendly Perl wrapper named adduser that prompts interactively for profile details, useradd is the universal compiled binary compiled from the shadow-utils suite. Because useradd accepts explicit command-line flags and reads standardized system configuration files without blocking on interactive prompts, it is the preferred tool for Ansible playbooks, Dockerfiles, Terraform provisioners, and production bash scripts.
When you create a new user without arguments, useradd consults /etc/default/useradd and /etc/login.defs to decide whether to allocate a home directory, which login shell to assign, and which UID range to select. Understanding how these defaults differ between Debian-based and Red Hat-based distributions prevents common configuration pitfalls such as missing /home directories or accidental assignment of the minimal /bin/sh shell.
What useradd Does and When to Use It
Under the hood, useradd performs an atomic transaction across four primary flat-file authentication databases in /etc: /etc/passwd (public account metadata including UID, primary GID, GECOS comment, home directory path, and login shell), /etc/shadow (password hashes and password aging policy metrics), /etc/group (group definitions and supplementary member lists), and /etc/gshadow (group password hashes and administrators). Before modifying these files, useradd acquires advisory file locks (.pwd.lock) to prevent race conditions when concurrent configuration management jobs run on the same host.
After registering the account entries in /etc, useradd checks whether home directory creation is enabled via the -m flag or the CREATE_HOME yes directive in /etc/login.defs. When instructed to build the home directory, it creates /home/<username>, copies hidden initialization dotfiles (.bashrc, .profile, .bash_logout) from the skeleton template directory /etc/skel, and recursively sets ownership to the newly allocated UID and primary GID while applying the permission mask controlled by HOME_MODE or UMASK.
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 useradd 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 useradd 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:
Before running administrative tasks or automation scripts, verify whether useradd is installed and inspect which binary path and version your shell resolves:
type -a useradd
useradd --version 2>/dev/null || man -f useradd
# Illustrative output (reviewed against documentation)
useradd is /usr/bin/useradd
useradd (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
useradd [OPTIONS] USERNAME
The useradd command follows a two-mode syntax: useradd [OPTIONS] USERNAME to create a new account, or useradd -D [OPTIONS] to inspect or update system-wide default values stored in /etc/default/useradd. The USERNAME operand must be a valid POSIX login name—typically starting with a lowercase letter or underscore, followed by up to 31 lowercase letters, digits, underscores, or hyphens.
Because useradd modifies protected authentication files in /etc and creates root-level subdirectories inside /home, it must be executed with superuser privileges via sudo or as root. By default, useradd creates the account in a locked state without a valid password hash (! or * in /etc/shadow), meaning password-based logins remain disabled until an administrator runs passwd USERNAME or provisions an SSH public key in ~/.ssh/authorized_keys.
0— Account created or defaults updated successfully.1— Cannot update password file (/etc/passwdor/etc/shadowlock contention or permission failure).2— Invalid command syntax or unrecognized option.3— Invalid argument supplied to an option (for example, non-existent group or malformed UID).4— Specified UID is already in use and the-o(--non-unique) flag was not provided.6— Specified primary or supplementary group does not exist in/etc/group.9— Specified username is already in use by an existing local or NSS account.12— Unable to create the home directory or copy/etc/skeltemplate files.
Important Options and Flags Reference
| Option / Flag | Long Form / Argument | Technical Behavior and Purpose |
|---|---|---|
-m | --create-home | Create the user's home directory if it does not exist and populate it with template files from /etc/skel. |
-M | --no-create-home | Do not create the user's home directory, overriding any CREATE_HOME setting in /etc/login.defs. |
-d | --home-dir HOME_DIR | Specify a custom path for the user's login directory instead of defaulting to /home/USERNAME. |
-s | --shell SHELL | Set the path to the user's login shell (such as /bin/bash, /bin/zsh, or /usr/sbin/nologin). |
-u | --uid UID | Explicitly assign a numeric User ID (UID) instead of selecting the next available UID automatically. |
-g | --gid GROUP | Set the name or numeric GID of the user's primary login group (the group must already exist). |
-G | --groups GROUPS | Comma-separated list of supplementary groups that the new user should also belong to. |
-r | --system | Create a system/service account with a UID lower than UID_MIN (typically 100-999) and no password aging. |
-e | --expiredate EXPIRE_DATE | Set the date on which the user account will automatically be disabled, formatted as YYYY-MM-DD. |
-c | --comment COMMENT | Add a descriptive string (GECOS field), such as full name, department, or ticket reference. |
In production environments, explicitly passing -m -s /bin/bash is a crucial best practice whenever provisioning interactive human accounts. On RHEL, Rocky Linux, and Fedora, CREATE_HOME is enabled by default in /etc/login.defs and the default shell is /bin/bash, whereas on Debian and Ubuntu, useradd without -m skips home directory creation and assigns /bin/sh (dash) unless instructed otherwise. Explicitly specifying both flags guarantees identical behavior across heterogeneous server fleets.
When creating service accounts for background daemons (such as Prometheus exporters, Node.js workers, or custom systemd services), combine -r (--system), -M (--no-create-home), and -s /usr/sbin/nologin. This combination allocates a UID in the reserved system range (below 1000), avoids cluttering /home, and ensures that even if the service is compromised, an attacker cannot spawn an interactive login session under that account.
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. Create a Standard User with a Home Directory and Bash Shell
The most common administrative task is creating an interactive login account for an engineer with a populated /home/username directory and /bin/bash as the default shell.
sudo useradd -m -s /bin/bash -c "DevOps Engineer" alex
sudo passwd alex
id alex
# Illustrative output (reviewed against documentation)
passwd: password updated successfully
uid=1001(alex) gid=1001(alex) groups=1001(alex)
The -m flag creates /home/alex and copies initialization files from /etc/skel, -s /bin/bash sets Bash as the interactive shell, and -c records the full role description in the fifth field of /etc/passwd. Notice that Linux user-private groups (UPG) automatically created a primary group named alex with matching GID 1001.
2. Create a User and Assign Supplementary Groups (sudo and docker)
When onboarding administrators or developers, you can assign their primary account and add them to supplementary privilege groups like sudo (or wheel on RHEL) and docker in a single atomic command.
sudo useradd -m -s /bin/bash -G sudo,docker,adm priya
id priya
# Illustrative output (reviewed against documentation)
uid=1002(priya) gid=1002(priya) groups=1002(priya),4(adm),27(sudo),998(docker)
Passing -G sudo,docker,adm appends priya to each listed group in /etc/group while preserving her dedicated primary user group (gid=1002(priya)). Always separate group names with commas and no spaces.
3. Create a Locked System Account for a Background Daemon
Application services such as web servers, message brokers, and monitoring agents should run under dedicated unprivileged system accounts rather than root.
sudo useradd -r -M -s /usr/sbin/nologin -c "Prometheus Node Exporter" node_exporter
getent passwd node_exporter
# Illustrative output (reviewed against documentation)
node_exporter:x:994:994:Prometheus Node Exporter:/home/node_exporter:/usr/sbin/nologin
The -r flag selects a system UID below 1000 (994 in this example), -M prevents creating a directory in /home, and -s /usr/sbin/nologin politely rejects any attempt to open an interactive shell.
4. Create a User with a Custom Home Directory Path and Explicit UID/GID
When mounting shared NFS storage or aligning container host UIDs across a cluster, you must enforce a deterministic UID, existing primary GID, and custom home directory path.
sudo groupadd -g 2050 webapps
sudo useradd -m -d /srv/webapps/deploy -u 2050 -g 2050 -s /bin/bash deploy
ls -ld /srv/webapps/deploy
# Illustrative output (reviewed against documentation)
drwxr-x--- 2 deploy webapps 4096 Oct 22 14:20 /srv/webapps/deploy
First, groupadd -g 2050 ensures the target primary group exists. Then useradd assigns UID 2050 (-u), primary GID 2050 (-g), and creates the custom home directory at /srv/webapps/deploy (-m -d).
5. Create a Temporary Contractor Account with an Automatic Expiration Date
For external auditors, interns, or short-term contractors, setting an account expiration date ensures access is revoked automatically without relying on manual offboarding reminders.
sudo useradd -m -s /bin/bash -e 2026-12-31 -c "External Security Auditor" auditor01
sudo chage -l auditor01
# Illustrative output (reviewed against documentation)
Last password change : Oct 22, 2026
Password expires : never
Password inactive : never
Account expires : Dec 31, 2026
Minimum number of days between password change : 0
Maximum number of days between password change : 99999
Number of days of warning before password expires : 7
The -e 2026-12-31 option converts the ISO-8601 date into the number of days since January 1, 1970 and writes it to the eighth field of /etc/shadow. Once that date passes, PAM blocks all logins—including SSH key authentication.
6. Inspect and Modify Default useradd Behavior (-D)
You can inspect the system-wide defaults that useradd applies when flags are omitted, and permanently update the default login shell for all future accounts.
sudo useradd -D
sudo useradd -D -s /bin/bash
sudo useradd -D | grep SHELL
# Illustrative output (reviewed against documentation)
GROUP=100
HOME=/home
INACTIVE=-1
EXPIRE=
SHELL=/bin/sh
SKEL=/etc/skel
CREATE_MAIL_SPOOL=no
SHELL=/bin/bash
Running useradd -D displays the active configuration from /etc/default/useradd. Running sudo useradd -D -s /bin/bash rewrites the SHELL= directive so future useradd invocations default to /bin/bash.
Real-World Workflows, Pipelines, and Shell Automation
Automated SSH-Only User Onboarding Script for Production Servers
In modern cloud infrastructure, human users authenticate exclusively via Ed25519 SSH keys rather than interactive passwords. This idempotent provisioning workflow creates the user, configures .ssh/authorized_keys with strict octal permissions (0700 and 0600), and verifies the account.
#!/usr/bin/env bash
set -euo pipefail
USERNAME="sre_admin"
SSH_PUBKEY="ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIJb8xYzExampleKeyDataForSREAdmin sre_admin@prod"
if ! id -u "$USERNAME" >/dev/null 2>&1; then
sudo useradd -m -s /bin/bash -G sudo -c "SRE Production Admin" "$USERNAME"
fi
USER_HOME="$(getent passwd "$USERNAME" | cut -d: -f6)"
sudo install -d -m 0700 -o "$USERNAME" -g "$USERNAME" "$USER_HOME/.ssh"
printf '%s
' "$SSH_PUBKEY" | sudo tee "$USER_HOME/.ssh/authorized_keys" >/dev/null
sudo chown "$USERNAME:$USERNAME" "$USER_HOME/.ssh/authorized_keys"
sudo chmod 0600 "$USER_HOME/.ssh/authorized_keys"
ls -la "$USER_HOME/.ssh"
# Illustrative output (reviewed against documentation)
total 12
drwx------ 2 sre_admin sre_admin 4096 Oct 22 15:02 .
drwxr-x--- 3 sre_admin sre_admin 4096 Oct 22 15:02 ..
-rw------- 1 sre_admin sre_admin 96 Oct 22 15:02 authorized_keys
Checking id -u makes the script safe to re-run in configuration management loops. Using install -d -m 0700 -o ... -g ... creates the .ssh directory with the exact ownership and permissions required by OpenSSH StrictModes in a single step.
Bulk Provisioning Users from a CSV Manifest in Bash
When setting up a training lab or migrating legacy accounts, administrators often receive a CSV file containing usernames, full names, and group memberships.
cat << 'EOF' > /tmp/new_users.csv
dev_maya,Maya Lin,developers
dev_liam,Liam Patel,developers
ops_noah,Noah Kim,sudo
EOF
while IFS=, read -r uname fullname grp; do
getent group "$grp" >/dev/null || sudo groupadd "$grp"
if ! id "$uname" >/dev/null 2>&1; then
sudo useradd -m -s /bin/bash -c "$fullname" -G "$grp" "$uname"
echo "Provisioned $uname ($fullname) in group $grp"
fi
done < /tmp/new_users.csv
# Illustrative output (reviewed against documentation)
Provisioned dev_maya (Maya Lin) in group developers
Provisioned dev_liam (Liam Patel) in group developers
Provisioned ops_noah (Noah Kim) in group sudo
The while IFS=, read -r loop parses each row safely without word-splitting on spaces inside the user's full name. Before calling useradd, getent group verifies that the supplementary group exists and creates it if needed.
Pipelines, Redirection, Quoting, and Shell Expansion
When embedding useradd 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
Never pass the -o (--non-unique) flag with -u 0 unless intentionally creating an alias root account—any account assigned UID 0 possesses full, unrestricted kernel superuser privileges regardless of its username. Additionally, never store plaintext passwords in command history by passing unhashed secrets to useradd -p.
The -p (--password) option in useradd expects an already-encrypted password hash as returned by crypt(3), NOT a plaintext password. If you run useradd -p MySecretPass user1, the literal cleartext string MySecretPass is written directly into /etc/shadow AND recorded in .bash_history and process audit logs (auditd), rendering the account unable to log in while exposing the secret. Always set passwords interactively via passwd, pipe hashes to chpasswd -e, or rely exclusively on SSH public keys.
To enforce least-privilege access across multi-user hosts, configure HOME_MODE 0750 (or 0700) in /etc/login.defs so newly created home directories are not world-readable (0755) by other local users. Furthermore, audit /etc/skel periodically to ensure no sensitive tokens or overly permissive umask overrides are copied into new user profiles.
GNU/Linux, BSD, and BusyBox Implementation Differences
While useradd is standard across Linux distributions using shadow-utils (Debian, Ubuntu, RHEL, Fedora, SUSE, Arch), default configurations vary significantly. Debian and Ubuntu ship with adduser (a high-level interactive script) alongside useradd (the low-level binary where -m is required to create /home/user). On RHEL, CentOS, Rocky Linux, and AlmaLinux, adduser is merely a symbolic link pointing directly to /usr/sbin/useradd, and -m is enabled by default.
On FreeBSD, OpenBSD, and macOS, useradd differs or is absent: FreeBSD uses pw useradd, OpenBSD provides a BSD implementation of useradd, and macOS manages local accounts through Directory Service (dscl or sysadminctl -addUser). On Alpine Linux minimal containers, BusyBox provides the lightweight adduser applet by default, though you can install standard useradd via apk add shadow.
Troubleshooting Common Errors and Diagnostics
useradd: cannot lock /etc/passwd; try again later.
Root Cause: Another process (such as vipw, usermod, passwd, or a crashed configuration management run) holds the lock file /etc/.pwd.lock or /etc/passwd.lock.
Resolution: Verify that no active user-management process is running with ps aux | grep -E 'user|passwd|vipw'. If no process is active, remove the stale lock files and retry.
pgrep -fa "useradd|usermod|passwd|vipw"
sudo rm -f /etc/.pwd.lock /etc/passwd.lock /etc/shadow.lock /etc/group.lock
useradd: group 'docker' does not exist
Root Cause: You passed a group name to -g or -G that has not yet been registered in /etc/group.
Resolution: Create the missing group first using groupadd (or groupadd -r for system groups) before running useradd.
sudo groupadd docker
sudo useradd -m -s /bin/bash -G docker alex
New user logs in to a bare '$' prompt without tab completion or history
Root Cause: The account was created on Debian or Ubuntu without -m and -s /bin/bash, causing /etc/passwd to assign /bin/sh (dash) and no home directory.
Resolution: Change the user's login shell to /bin/bash with usermod -s and create/populate their home directory with mkhomedir_helper.
sudo usermod -s /bin/bash alex
sudo mkhomedir_helper alex
Alternatives, Related Commands, and Related Tutorials
- How to List Users in Linux (Local, System, and Network Accounts) — Practical syntax, flags, and examples for
getent. - How to Remove a User in Linux with the userdel Command — Practical syntax, flags, and examples for
userdel. - How to Add a User to a Group in Linux (usermod and gpasswd) — Practical syntax, flags, and examples for
usermod. - usermod Command in Linux: Modify User Accounts, Shells, and Groups — Practical syntax, flags, and examples for
usermod. - 25 Best Linux Commands Every Sysadmin Should Know — Core command-line utilities for daily Linux server administration.
- How to Find a File in Linux from the Command Line — Practical file search patterns across Linux directories.
- Linux Commands Knowledge Hub (#linux-commands) — Browse all Linux command-line tutorials and system administration references.
Authoritative References and Official Documentation

The Linux Command Line, 2nd Edition: A Complete Introduction
Frequently Asked Questions
Quick answers to common questions and configurations
/etc/login.defs does not enable automatic home directory creation for raw useradd calls by default. Always pass the -m (--create-home) flag—for example, sudo useradd -m -s /bin/bash username—to ensure the home directory is created and populated from /etc/skel./usr/sbin/nologin username. The -r flag allocates a system UID below 1000, -M prevents creating a directory under /home, and -s /usr/sbin/nologin blocks interactive shell sessions./etc/skel into the new user's home directory and updates their ownership to match the new user's UID and GID.Editorial Disclosure: Website Vidya is supported by our readers. When you purchase hosting, tools, or software through our verified partner links, we may earn an affiliate commission at no extra cost to you. We only recommend solutions we trust and rigorously verify.
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.
Most Read Guides
TrendingUbuntu Server Not Booting? 10 Simple Steps to Fix It Fast
How to Create a 3D Button in HTML and CSS: Easy Steps
How to Install Python and Pip on Ubuntu 24.04 LTS
How to Install Nginx on Ubuntu 24.04
How to Install Python on Ubuntu 24.04 LTS
Related Technical Guides
Tested runbooks, server administration walkthroughs, and troubleshooting guides

Join the Conversation & Perspective
Have thoughts, counterpoints, or reflections on this story? Engage directly with fellow readers and editorial contributors.
No comments on this guide yet. Be the first to share your thoughts or ask a question!