Why is hostname and $HOSTNAME different?

Tom Mitchell niftyubuntu at niftyegg.com
Wed May 11 17:06:55 UTC 2022


On Wed, May 11, 2022 at 9:31 AM Bo Berglund <bo.berglund at gmail.com> wrote:
>
> This is in Ubuntu Server 20.04.4 LTS
>
> I have some scripts that use the hostname to switch some paths when running.
> It has been OK for a long time but now after I did a router f/w upgrade my
> scripts fail.
>
> And I think this is the cause of it all:
>
> $ hostname
> ubuntusrv
> $ echo $HOSTNAME
> ubuntuserv
>
> Notice the difference in the return from these commands, which I thouight would
> be identical.
>
> Inside the scripts I use this construct:
>
> if [ "$HOSTNAME" == "ubuntuserv" ]; then
>   URLFILE="$HOME/www/url_strm.txt"   #Main web server file path
> else
>   URLFILE="$HOME/lan/url_strm.txt"   #Secondary device file path
> fi
>
> And it has worked fine for ages, but failed today after the router update.
>
> Can the DHCP server in the router affect the hostname of a device which is using
> it to get its IP address?
> I had to go over and re-enter the DHCP reservations after a f/w update on the
> router forced me to reset to factory and re-enter the complete config by hand.
>
> If so what is the correct way in a script to get the *real* hostname which is
> shown on the command line in terminal?
>

The easy answer first: Yes DHCP can set the hostname.  If that is how
you set it.

Next search to see how you set the hostnames (yes plural) for your machine.
Start with /etc/hostname
Next /etc/hosts
Then DNS
Note that hostname is per network interface and that includes
localhost 127.0.0.1
I have different names and IP addresses for local loopback, wired
ethernet and WiFi.

These are close enough to be a simple typo
  ubuntusrv
  ubuntuserv

It is not silly to just search for each. Start in the obvious
locations in and under /etc
$ find /etc -type f -print | xargs grep ubuntusrv
$ find /etc -type f -print | xargs grep ubuntuserv

DHCP can set a lot of parameters so review that machine as well.
The local DHCP client can accept, ignore  or override.

DNS is harder but "dig" and "host" let you see most of what you need
to see quickly.
A DHCP server can get hostnames from local files, local configurations and DNS.
Do not ignore other net services and authentication services, even a yp server.
In a mixed Windows, MacOS, Ubuntu, Fedora ... world it can get interesting.




More information about the ubuntu-users mailing list