The hostname command without any options can be used to view the hostname of the system. In this example, the hostname is fs1.sample.com.
~]# hostname fs1.sample.com
If a Debian family distribution is being used, the hostname command reads the contents of the /etc/hostname file.
~]# cat /etc/hostname fs1.sample.com
If a Red Hat family distribution is being used, the hostname command reads the contents of the /etc/hostname or /etc/sysconfig/network file.
~]# cat /etc/hostname fs1.sample.com ~]# cat /etc/sysconfig/network HOSTNAME=fs1.sample.com
View hostname only
It is fairly common for the hostname command to display both the machine name and the domain name, or the fully qualified domain name (FQDN). In the prior example, the hostname command displayed both the machine name (fs1) and the domain name (sample.com). The -s or --short option can be used to only display the machine name. In this example, only the machine name fs1 is displayed.
Technically, the -s or --short option will only read the hostname up to the first period. If the machine name contains a period, such as fs.1, only "fs" would be displayed.
~]# hostname -s fs1
Temporarily change hostname
The hostname of the PC can be temporarily changed by using the hostname command followed by the new hostname. In this example, the hostname is temporarily changed to new.sample.com. This does not update the /etc/hostname or /etc/sysconfig/network file, meaning this is not a permanent change.
~]# hostname new.sample.com
Permanently change hostname
To permanently update the hostname, change the hostname in the /etc/hostname or /etc/sysconfig/network file.
While not required, there is typically an entry in the DNS server with the hostname to IP address mapping. It is common for the hostname to be the machine name followed by the domain name. In this example, the machine name is fs1, and the domain name is sample.com.
Using hostname on the command line
Let's say you have a command that needs to get the hostname of the system. Place the hostname command instead of parenthesis and a leading dollar symbol.
~]# command -g hello $(hostname -s) -e world
Using hostname in a BASH shell script
The -i option can be used . . .
. . . to display the system IP address.