Managing local users with useradd and usermod
- Version
- unversioned
- Review
- Draft
Summary#
useradd, usermod and userdel create, change and remove local accounts. They need root.
Syntax#
sudo useradd -m -s /bin/bash alice
sudo passwd alice
sudo groupadd deploy
sudo usermod -aG deploy alice
sudo usermod -L alice
sudo userdel -r alice
-m creates the home directory and -s sets the login shell. -aG appends supplementary groups. -L locks the password, and userdel -r also removes the home directory and mail spool.
Example#
Run this as root on a disposable system or container. It stops if the demonstration user or group already exists, and removes both when it ends.
(
set -eu
user=dl-demo
group=dl-team
if getent passwd "$user" >/dev/null || getent group "$group" >/dev/null; then
echo 'demonstration account already exists' >&2
exit 1
fi
trap 'userdel -r "$user" 2>/dev/null || true
groupdel "$group" 2>/dev/null || true' EXIT
groupadd "$group"
useradd -m -s /bin/sh "$user"
usermod -aG "$group" "$user"
getent passwd "$user" | cut -d: -f6,7
id -nG "$user" | tr ' ' '\n' | grep -x "$group"
)
Expected output#
/home/dl-demo:/bin/sh
dl-team
Common mistakes#
usermod -G deploy alice without -a replaces all supplementary groups and can remove administrator access. The user must start a new login session to receive new groups. Without root, these commands fail, for example because they cannot lock /etc/passwd. useradd does not set a password, and by default may not create a home directory, so pass -m. Debian and Ubuntu also offer the interactive adduser.
Version applicability#
This entry describes the tools from shadow-utils 4.19 and the equivalent Debian packages. Defaults such as home directory creation vary between distributions.
Sources#
- Attribution
- DevLookup contributors
- License
- CC-BY-4.0