How to safely change username and hostname?

I installed a fresh Ubuntu Gnome 14.04.3 today, but I just notice that I reversed the username and hostname during installation.

To illustrate this, when I open a terminal, the prompt looks like :

myhost@myname:~$

instead of

myname@myhost:~$

It is the unique user (so it is the normal admin).

How can I fix this problem ?


Changing the hostname

Change the hostname in the following two files:

  • /etc/hostname
  • /etc/hosts

(You'll need to use sudo to edit these files. Eg. sudo nano /etc/hostname)

Changing the username

First, set a password for root:

sudo su
passwd root

Then reboot the machine. When you see the login screen, switch to a virtual terminal using CtrlAltF4. Login with the username root and the password you set previously.

It's now safe to change the username using the following three steps:

  1. Rename the user:

    usermod -l newUsername oldUsername
    
  2. Change the name of the user directory and all daughter directories to match the new username and update the filepaths:

    mv /home/oldUsername* /home/newUsername*
    
  3. Update the user database:

    usermod -d /home/newUsername* -m newUsername