Options in usermod Command in Linux
-d, --home: This option changes the user's home directory.
For example -
usermod -d /new/home/directory username
Output:
No output, but the home directory of 'username' has been changed to '/new/home/directory'.
This command changes the home directory of 'username' to '/new/home/directory'.
-s, --shell: This option changes the user's login shell.
For example -
usermod -s /bin/ksh username
Output:
No output, but the login shell of 'username' has been changed to '/bin/ksh'.
This command changes the login shell of 'username' to '/bin/ksh'.
-a, --append: This option is used with -G and adds the user to the supplementary group(s).
For example -
usermod -a -G group1,group2 username
Output:
No output, but 'username' is now a member of 'group1' and 'group2'.
This command adds 'username' to 'group1' and 'group2' without removing them from any other groups.
Example Usages
Changing a user's home directory:
usermod -d /new/home/directory username
Output:
No output, but the home directory of 'username' has been changed to '/new/home/directory'.
Explanation: This usage of the usermod command in Linux alters the home directory of the user.
Adding a user to additional groups:
usermod -a -G group1,group2 username
Output:
No output, but 'username' is now a member of 'group1' and 'group2'.
Explanation: This usage of the usermod command in Linux adds the user to additional groups without removing them from their current groups.
Tips
Always make sure you have administrative rights or root access before attempting to modify user accounts with the usermod command in Linux. Without these rights, the command may not execute successfully.
When changing a user's home directory, it's a good practice to also move the contents of the old directory to the new one using the -m or --move-home option.
Be cautious when changing the login shell. Make sure the new shell is installed and configured correctly. A wrong shell can prevent the user from logging in.
Advanced Use Cases of usermod Command in Linux
Locking a user's password:
usermod -L username
Output:
No output, but the password for 'username' has now been locked.
Explanation: This command locks the password of 'username', making it impossible for them to login until the password is unlocked.
Expire a user's password:
usermod --expiredate 1 username
Output:
No output, but 'username''s password is now expired and they will be prompted to change it at their next login.
Explanation: This command sets the expiry date of 'username''s password to 1 day after the account was created, effectively expiring the password immediately.
Change user's primary group:
usermod -g new_group username
Output:
No output, but 'username''s primary group has been changed to 'new_group'.
Explanation: This command changes 'username''s primary group to 'new_group'.