1. Introduction

There are many times when we need to use aliases for hosts in Linux. For instance, perhaps a hostname is too long or difficult to remember and we want to use it several times, or maybe we need to test a hostname during our programming. In this tutorial, we’ll explore three ways to set an alias for a hostname.

2. Using SSH Config

Let’s assume that we want to connect to a host with a long name via ssh:

$ ssh [email protected] -p 3370

It’s too long to remember, and if we use it several times, we can save typing (and reduce mistakes) by shortening it:

$ ssh myhost

For this purpose, we should first edit the ~/.ssh/config file. This file may not exist, and in that case, it will be created after modification:

$ nano ~/.ssh/config

Let’s edit the settings in this file to acquire the desired configuration:

Host myhost
   User alongusername
   HostName sampleserver.verylongdomainname.com
   Port 3370

We should note that the default port of SSH is 22 and if we use the default port, we can skip the last line.

After saving our changes to the file, we’ll be able to easily SSH by specifying the host alias.

3. Using an Environment Variable

An environment variable is an object that has a name and holds a value or path. Every time we start a session in Linux, the system loads configuration files and environment variables accordingly.

Setting an alias using an environment variable allows us to access the variables in all commands and applications. For instance, instead of:

$ tracepath sampleserver.verylongdomainname.com

We could reduce this long name to something considerably shorter, such as:

$ tracepath $myhost

We should note that environment variables always start with the $ character.

Now, let’s edit the ~/.bashrc file to specify our variables:

$ nano ~/.bashrc

We can go to the end of the file and add the line:

export myhost='sampleserver.verylongdomainname.com'

Finally, after saving the file, we can also run this command to take effect without rebooting:

$ exec bash -l

This will replace our current shell with a new Bash shell run as a login shell.

Now, we can use this variable in all commands like curl, ping, ssh, and more.

4. Using the hosts File

Linux operating systems use the hosts file to translate hostnames or URLs into IP addresses.

Let’s start editing the /etc/hosts file. We need root access for this:

sudo nano /etc/hosts

At the end of this file, we can add the IP and the hostname:

192.168.1.100 myhost

We can also assign several names to one IP:

192.168.1.100 myhost1 myhost2

This change takes effect immediately without further action on our part.

5. Conclusion

In this tutorial, we’ve looked at three ways to alias a hostname in Linux. By changing the SSH config, we can set username, hostname, and port for easy use. Moreover, we can use environment variables to assign our desired hostnames to variables, or we can also assign a hostname to an IP by editing the /etc/hosts file.