Getting Hostname in Bash in Linux in 3 Ways

Getting the hostname of the node running a program can be useful in various scenarios, such as creating logs with the hostname, identifying which node a script is running on, or configuring a distributed system with different nodes. In Bash, there are several ways to retrieve the hostname of the machine, as mentioned in the previous post.

In Bash, you can get the hostname of the node in at least 3 ways:

Use the variable $HOSTNAME

The first method is to use the $HOSTNAME variable, which is a Bash environment variable that contains the name of the current hostname. This variable is set by the Bash shell at startup and can be accessed by any Bash script. However, it is worth noting that the value of $HOSTNAME may not always match the actual hostname of the machine, especially if the variable is manually set or modified.

$ echo $HOSTNAME

Use the hostname command

The second method is to use the hostname command, which is a utility that retrieves and sets the hostname of the machine. When invoked without any arguments, the hostname command prints the current hostname of the machine to the standard output. This method is useful when you need to retrieve the hostname from within a script and store it in a variable for further processing.

$ hs=`hostname`
$ echo $hs

Read the content of the Linux kernel /proc/sys/kernel/hostname file

The third method is to read the content of the /proc/sys/kernel/hostname file, which contains the current hostname of the machine. This method is similar to using the hostname command, but it reads the hostname from a system file instead of invoking a command. This method is useful when you need to quickly retrieve the hostname from the command line without invoking a command.

$ cat /proc/sys/kernel/hostname

Eric Ma

Eric is a systems guy. Eric is interested in building high-performance and scalable distributed systems and related technologies. The views or opinions expressed here are solely Eric's own and do not necessarily represent those of any third parties.


Leave a Reply

Your email address will not be published. Required fields are marked *