Change user name in UNIX

 

I have been getting a lot of questions about how to change a user name under UNIX, and how is the best practice to do so, or how to change the UID; In this tutorial, I will be showing you how to change a user account and what is the logic behind all the steps involved.Unix

This tutorial should work for all UNIX based systems like centOS, Ubuntu, Fedora too.
Note:
You can NOT change the username if that user is logged in. So, you may need to create another account (then log in) to alter your own account.

Changing the user name:
sudo usermod -l new-name old-name

The name of the user will be changed from old-name to new-name. Nothing else is changed. In particular, the user’s home directory name should probably be changed to reflect the new login name. I will be explaining this later in this post.

Changing the user ID (UID number):
sudo usermod -u UID username

This will change the numerical value of the user’s ID (UID). This value must be unique, unless the -o option is used. The value must be non-negative. Values between 0 and 99 are typically reserved for system accounts. Any files which the user owns and which are located in the directory tree rooted at the user’s home directory will have the file user ID changed automatically. Files outside of the user’s home directory must be altered manually. However, this can be done using this simple command:

# find / -user 5001 -print0 | xargs -0 chown -h 10000

Note that the 5001 UID in this example is the old ID, while the 10000 is the new one. Replace with your users IDs as needed.

Changing the user home directory:

Although this is an optional operation, I would highly recommend that home directory to be changed after a username change to reflect that change. In all UNIX-based systems, the default home directory for any giver user is /home/username. (except for “root” user, where the home directory is /root)

To change the user’s home directory use:

sudo chomd -m -d HOME_DIRECTORY username

Where HOME_DIRECTORY is the full path for the requested home directory. the “-m” option, which can only be used with -d (directory), is used to move the current files from the old home directory to the new one. You can omit this option if you want to start a with an empty directory.

Changing the group name:

This might also be needed sometimes, specially after a username change, in order to change the group name assigned to that altered user. To do so, issue the following command:

sudo groupmod -n new-group-name old-group-name

** To verify the changes, use the command “id user”.