It's a quite simple asked question I think: What are the key differences between using environment variables just like $HOSTNAME and `hostname`. Where is which appropriate, why are there two possibillities to represent them?
An environment variable is set once and for all (for a given process; when a process launches another, the child inherits the parent's environment). So accessing
$HOSTNAME directly reads a value in memory. In contrast, each time you evaluate the command substitution
`hostname` (also spelled
$(hostname)), this executes the
In the case of
hostname, in practice, it doesn't make any difference.
$HOSTNAME is marginally faster. In principle,
$HOSTNAME can be wrong if you've run
$(hostname) can be wrong if you put some different
hostname program on your
$PATH), and only
hostname keeps up-to-date if you change your host name.
There's often (but not always) a
HOSTNAME environment variable because it's often used (e.g. in shell prompts) and almost never changes. There's a
hostname command (on most systems) to set the value of
HOSTNAME=$(hostname)) and to change the host name (
hostname $(cat /etc/hostname), typically done early in the boot process).
It is appropriate to depend on the commands which fetch the current value than the variables which can get stale over a period of time in the unattended sessions.
[centos@abc ~]$ /bin/hostname abc.dns.com [centos@abc ~]$ echo $HOSTNAME abc.dns.com [centos@abc ~]$ uname -n abc.dns.com [centos@abc ~]$ sudo /bin/hostname xyz.dns.coom [centos@abc ~]$ uname -n xyz.dns.coom [centos@abc ~]$ /bin/hostname xyz.dns.coom [centos@abc ~]$ echo $HOSTNAME abc.dns.com [centos@abc ~]$
I think its clear that
$HOSTNAME is a shell variable, which is expanded/evaluated by capturing the output of
/bin/hostname at the start of the shell initialization and its not updated everytime or if the hostname is dynamic. Depending on the output of
/bin/hostname is more reliable than $HOSTNAME unless it is the same script or program that has already evaluated the name of the host in the same program space.
Well, in short, output of the commands
/bin/uname -m is more appropriate method to know the hostname than just using $HOSTNAME (which could become stale as any other normal SHELL variable).
If you are curious to know how does shell gets $HOSTNAME inherited, then its proper to know that shell reads its global initialization (rc) files like /etc/profile (or /etc/bashrc) which has this variable defined from again output of
(It is also important to know that programs other than shell without prior executing
/bin/hostname command can have HOSTNAME variable defined/initialized because of the system startup script called