2024-09-26
useradd
At its core, useradd
creates a new user account. The simplest form is:
sudo useradd username
Replace username
with the desired username. This command creates a new user with a home directory in /home/username
and a default shell (/bin/bash
usually). The sudo
prefix is essential, as only the root user or users with sudo privileges can create new accounts.
Let’s create a user named “newuser”:
sudo useradd newuser
Verify the user’s creation:
cat /etc/passwd | grep newuser
This command searches the /etc/passwd
file (which contains user account information) for the “newuser” entry.
You can specify a custom home directory using the -d
or --home-directory
option:
sudo useradd -d /home/users/newuser2 newuser2
This creates newuser2
with a home directory located at /home/users/newuser2
. Note that the directory must exist before running the command, or you’ll encounter an error. You can create it beforehand using mkdir -p /home/users/newuser2
.
The default shell is usually Bash (/bin/bash
), but you can change it using the -s
or --shell
option:
sudo useradd -s /bin/zsh newuser3
This creates newuser3
with Zsh as their default shell.
Each user and group has a unique ID. You can specify these using -u
(UID) and -g
(GID):
sudo useradd -u 1001 -g 1001 newuser4
This creates newuser4
with UID and GID both set to 1001. Be cautious when manually setting UIDs and GIDs to avoid conflicts.
You can add the user to a specific group using the -g
option:
sudo useradd -g sudoers newuser5
This adds newuser5
to the sudoers
group, granting them sudo privileges (assuming sudo
is configured correctly). Note that simply adding a user to the sudoers
group doesn’t automatically grant sudo privileges; you’ll typically need to edit /etc/sudoers
using visudo
.
To add a user to multiple groups, use the -G
option multiple times or list them comma separated:
sudo useradd -G audio,video newuser6
This adds newuser6
to both the audio
and video
groups.
System accounts are typically used for services and don’t have a home directory. Use the -M
option to prevent home directory creation:
sudo useradd -M -s /sbin/nologin systemuser
This creates systemuser
without a home directory and with /sbin/nologin
as the shell, preventing login.
You can create a user based on a template account using the -k
option:
sudo useradd -k /etc/skel/template newuser7
This will copy the contents of the /etc/skel/template
directory (assuming it exists and contains files and settings for new users) to the newuser7’s home directory.
These examples illustrate the power and flexibility of the useradd
command. Remember always to use sudo
and exercise caution when modifying system settings. Further exploration of the man useradd
page is highly recommended for a complete understanding of all available options.