In this tutorial we'll focus on how to edit the hostname in Ubuntu and Debian Linux distributions but instructions are useful for most distributions.
The device's hostname in Linux is stored in two configuration files located in the directory /etc/.
The files /etc/hostname and /etc/hosts. These are the two files we will work on to edit the hostname.
This file only contains the hostname.
/etc/hosts:
The file /etc/hosts maps the host and ip addresses, it translates from IP addresses (X.X.X.X) to www.domain.com or @Anything. In this file you can add all the local network devices ip addresses and hostnames to avoid domain name resolution. Usually the file hosts has 3 columns, the IP address, the hostname and an alias for the hostname, it can have more than one alias or may not have at all as in the example below.
127.0.0.1 localhost
127.0.0.1 linuxhint.com
# The following lines are desirable for IPv6 capable hosts
::1 localhost ip6-localhost ip6-loopback
ff02::1 ip6-allnodes
ff02::2 ip6-allrouters
To verify our current hostname we can read the files mentioned above or in the terminal run:
hostname
We can also verify our hostname using the command less to read the /etc/hostname file, type:
less /etc/hostname
As you see here the hostname is LinuxHint.COM, while Montsegur is commented.
To change our hostname using the command hostnamectl run:
hostnamectl set-hostname
Note: if you get an error while running hostnamectl continue to “hostname” command.
After running hostname again we see the hostname was changed to LinuxHint2.
After changing our hostname with the commands hostname (as explained below) or hostnamectl edit the file /etc/hosts using nano or vi text editors to update your new hostname, add a line below previous hostnames with the new one:
nano /etc/hosts
Then let's edit the file /etc/hostname and edit the file adding the new hostname:
nano /etc/hostname
We can also change our hostname using the command hostname:
hostname
After changing our hostname we need to restart our networking services:
On Debian and Ubuntu Linux distributions try:
service networking restartIt may also be:
service hostname restartFor CentOS and Fedora:
/etc/init.d/network restartOf course you can also reboot your device and changes will take effect. At any time we can type “hostname” to see the current hostname, commands hostname or hostnamectl aren't persistent, for the change to be persistent remember to update files /etc/hosts and /etc/hostname after changing your hostname. Changes won't take visual effects on the working terminal but if you open a new terminal it will show the new hostname after the username.
I hope you found this tutorial useful to get your data fully removed, should you have any inquiry contact us opening a ticket support at LinuxHint Support. Keep following LinuxHint for more tips and updates on Linux.