How to change hostname on a Linux server

This simple ‘how to’ will show you the steps to change the hostname of Linux server. The host name is the identifier of a server. A good practice is to set a meaningful name that will help you to easily identify your servers.

It’s stored in the “/etc/hostname” configuration file. To change we’ll start by replacing the name in that file with “cb-demo-13” or a hostname by your choice:

echo “cb-demo-13” > /etc/hostname

This changes the configuration, but your Linux system will read that file only on boot so we would like to update the running configuration by executing:

hostname `cat /etc/hostname`

You don’t need to restart your system.

By reloading the hostname from the “/etc/hostname” file the new name will be used for any new sessions started on the server, but as you’ll notice the current sessions prompt won’t update and will keep showing the previous name.

To fix that you can re-export the variable that builds the prompt.

For Debian and Ubuntu:

export PS1=’\u@$(hostname):\w\$ ‘

or on Fedora and CentOS:

export PS1='[\u@$(hostname) \w]\$’

With that step your current prompt will update and show the new hostname:

[root@cb-demo-13 ~]#

Enjoy your server and remember that good naming is not only a nice gesture to your server, but an important and professional practice.