How to Rename a Linux User
What if after installing a Linux OS you found that you made a typo in the username. Reinstalling the whole OS just to fix a typo doesn’t sound rational.
One solution can be removing the wrong user and creating a new one, with a correct name. But in that case, all programs that had configs in the user’s home directory will be messed up, which is very bad.
The correct way of renaming a Linux user and his home directory is to use the usermod
command:
🚀 ~ usermod -l <new_username> <old_username>
Then, we need to set a home directory for our new user:
🚀 ~ usermod -md /home/<new_username> <new_username>
Here, the -d
flag sets the home directory for our new user, and the -m
flag moves all contents from the old user’s home directory.
We also need to change the user’s default group, which is the same as the username in most cases:
🚀 ~ groupmod -n <new_username> <old_username>
And, finally, if your hostname is like <username-desktop>
or similar, you might want to change it, too. You need to edit both /etc/hostname
and /etc/hosts
files to do that.
🚀 ~ echo <new_username>-desktop | tee /etc/hostname # or 'sudo tee'
# backup first
🚀 ~ cp /etc/hosts /etc/hosts.bak
# then
🚀 ~ sed -i 's/<old_username>/<new_username>/gI' /etc/hosts
Â
Important! All commands above need to run under root
or with sudo
.
Important! The changes in /etc/hostname
and /etc/hosts
will take effect only after rebooting the system.
Important! If you want to rename the currently logged-in user, then it won’t work because that user is used by certain processes. The workaround here is to switch to Virtual Console (Ctrl+Alt+F1-F6), log in as root
, kill all that processes with kill <pid>
, do the necessary operations of renaming the user, and re-login again by switching to GUI login screen (Ctrl+Alt+F7).
Â
References
“How to rename Linux users and their home directory” by Shane Rainville (August 28, 2020)Â
“Ubuntu Linux Change Hostname (computer name)” by Vivek Gite (August 19, 2020)Â
“kill(1) — Linux man page”