DEV Community

Cover image for hostname Command in CLI
Baransel
Baransel

Posted on • Originally published at baransel.dev

hostname Command in CLI

Sign up to my newsletter for more tutorials!.

You can find and set the name of your computer to make it easier for people to discover on a network using the hostname command.

hostname

You will get a result saying your computer name and in my case it says baransel.local

The first part of the result is the name of the computer and the second part is the name of the domain.

hostname -s

You can run the command above to return just the computer name.

The result will be simply baransel this time.

hostname -d

Similarly, just use the command above to find out which domain you are on.

hostname -i

You can find the IP address for the hostname using the command above.

hostname -a

A hostname can be given a name, and you can find all the aliases of the computer you are using by typing the command above.

If there are no aliases, your real hostname will be returned.

How to Change hostname

You can change the hostname of the computer by typing the following command:

hostname baranseldev
Enter fullscreen mode Exit fullscreen mode

Now when you run the hostname command it will only show baranseldev.

This change is temporary and not particularly helpful.

To permanently change your hostname, use the nano editor to open /etc/hosts.

sudo nano /etc/hosts
Enter fullscreen mode Exit fullscreen mode

You will need elevated privileges to edit the hosts file, and you can use the sudo command as shown above or switch users to root using the su command.

The /etc/hosts file has details about your computer and other machines on your network or other networks.

By default, your /etc/hosts file will contain something like:

127.0.0.1 localhost.localdomain localhost
Enter fullscreen mode Exit fullscreen mode

The first item is the IP address to resolve for the computer. The second item is the computer's name and domain, and each subsequent field provides an alias for the computer.

To change the hostname, you can simply replace localhost.localdomain with the computer name and domain name.

Example:

127.0.0.1 baranseldev.mydomain localhost
Enter fullscreen mode Exit fullscreen mode

After saving the file, run the hostname command, and you will get the following result:

baranseldev.mydomain
Enter fullscreen mode Exit fullscreen mode

Similarly, hostname -d is shown as mydomain and hostname -s is shown as baranseldev.

Top comments (0)