Linux usermod command
The usermod
command in Linux is used to modify or update a user’s account settings. With usermod
, you can change various attributes of an existing user, such as their username, home directory, group memberships, login shell, and more.
1. Basic Syntax of usermod
The syntax for the command is:
This command requires administrative privileges (sudo
) and is followed by various options to specify the modifications.
2. Examples of usermod
with Expected Output
Example 1: Changing a User’s Primary Group
To change a user’s primary group, use the -g
option.
Command:
Expected Output:
There is no output on success. This command changes alice
's primary group to developers
. You can verify the change by checking the /etc/passwd
file or using the id
command:
Expected Output:
Example 2: Adding a User to a Secondary Group
To add a user to additional groups (secondary groups), use the -aG
option. The -a
(append) flag is important; without it, -G
would replace the user's current groups instead of adding new ones.
Command:
Expected Output:
This command adds alice
to the sudo
and developers
groups without affecting her other group memberships. To confirm, use:
Expected Output:
Example 3: Changing a User’s Username
To change a user’s username, use the -l
option.
Command:
Expected Output:
This command changes the username from alice
to alicia
. However, the home directory remains the same unless specified with the -d
option. Verify by checking the /etc/passwd
file.
Example 4: Changing a User’s Home Directory
To change the home directory, use the -d
option and -m
to move existing files to the new directory.
Command:
Expected Output:
This command changes the home directory for alicia
to /home/newalice
and moves all files from the old home directory to the new one. Check the new home directory by listing it:
Example 5: Locking and Unlocking a User Account
To lock a user’s account, preventing login, use the -L
option.
Command:
Expected Output:
This locks alicia
's account by placing an exclamation mark (!
) before the encrypted password in /etc/shadow
. To unlock the account, use:
3. Common Options for usermod
- -g <group>: Change the primary group.
- -aG <group1,group2,...>: Add to secondary groups.
- -d <directory>: Specify a new home directory.
- -m: Move the contents of the current home directory to the new directory.
- -l <newname>: Change the username.
- -s <shell>: Change the default shell (e.g.,
/bin/bash
). - -L / -U: Lock or unlock a user account.
4. Important Considerations
- Username Change: Changing usernames can affect ownership of files and permissions, so it should be done cautiously.
- Locking Accounts: Use account locks for temporary suspensions; this does not delete the user or their files.
The usermod
command is versatile and powerful, but each change must be carefully implemented to ensure the account functions as intended.