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:
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.
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:
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.
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.