usermod - Linux


Overview

The usermod command in Linux is used to modify a user account, making it a crucial tool for system administration. It allows the administrator to change settings such as user name, home directory, shell, and group affiliation, among others.

Syntax

The basic syntax of usermod is as follows:

usermod [options] LOGIN
  • options: These are the flags that determine what changes will be made to the user’s account.
  • LOGIN: The username of the account to modify.

Options/Flags

Here are the most commonly used options for usermod:

  • -c, --comment COMMENT : Add or update the GECOS field of the user account.
  • -d, --home HOME_DIR: Set a new login home directory.
  • -e, --expiredate EXPIRE_DATE: Set the date on which the user account will be disabled.
  • -g, --gid GROUP: Change the primary group ID.
  • -G, --groups GROUPS: Add the user to supplementary groups.
  • -l, --login NEW_LOGIN: Change the username.
  • -L, --lock: Lock the user account.
  • -m, --move-home: Move the user’s home directory to a new location.
  • -s, --shell SHELL: Change the user’s login shell.
  • -U, --unlock: Unlock the user account.
  • -u, --uid UID: Assign a new user ID to the user.

Examples

  1. Changing the login name of a user:
    usermod -l newname oldname
    
  2. Setting a new home directory:
    usermod -d /new/home -m username
    

    This also moves all files from the user’s current directory to the new one.

  3. Adding a user to additional groups:
    usermod -aG sudo,adm username
    
  4. Locking and unlocking a user account:
    usermod -L username  # Lock the account
    usermod -U username  # Unlock the account
    

Common Issues

  • Permission Denied: usermod must be run with root privileges. Use sudo before your usermod command to avoid this issue.
  • User Does Not Exist: Verify the username with cat /etc/passwd.
  • Group Does Not Exist: When changing group IDs, ensure the specified group exists, or use groupadd to create it.

Integration

usermod can be combined with other commands for scripts and maintenance tasks. For example, to backup a user’s home directory before changing it:

tar czf /backups/username.tar.gz /home/username && usermod -d /new/home -m username

Another practical integration is with awk for conditional modifications:

awk -F':' '$3 > 1000 {print $1}' /etc/passwd | xargs -I {} sudo usermod -L {}

This command sequence locks out all users with an ID greater than 1000.

  • adduser, useradd: Commands to add users.
  • passwd: Modify the user’s password.
  • userdel: Delete a user account.
  • chage: Change user password expiry information.

Consult the official documentation or use man usermod for a more detailed look at additional options and behaviors.