17

I am wondering how can I get the hostname (fully qualified domain name) of the machine I am working on?

Here is my script:

 #! /bin/sh    
 hostname=$(host $ipaddr | awk '{print substr($NF,1,length($NF)-1)}')
 echo $hostname
 $h= get the current hostname
 if [ $hostname -ne $h ]
 then
//instructions
 fi
6
  • hostname -s should get the short (minus rest of FQDN) hostname... i.e. hostname=$(hostname -s)... ?
    – Kinnectus
    Jul 23, 2015 at 11:31
  • $HOST environmental variable contains a hostname of the machine.
    – theoden8
    Jul 23, 2015 at 12:08
  • 1
    Can the OP update the question as to whether they want the FQDN or just the "short" hostname?
    – Kinnectus
    Jul 23, 2015 at 13:03
  • yes, i need fully qualified domain name.
    – researcher
    Jul 23, 2015 at 13:40
  • echo $HOST display nothing
    – researcher
    Jul 23, 2015 at 13:40

2 Answers 2

34

Use hostname or uname -n to get the kernel hostname (nodename).

hostname -s will give just the first component of the same.

Use hostname -f to get the FQDN – it additionally tries to translate the hostname to an IP address, then back to a domain name.

4
  • resolved with hostname -f, please how can modifiy this condition: $h= get the current hostname if [ $hostname -ne $h ] Thanks a lot.
    – researcher
    Jul 23, 2015 at 13:48
  • 2
    h=$(hostname -f) Jul 23, 2015 at 13:52
  • var=$(hostname -f) echo $var if [ $hostname -ne $var ] [: Illegal number:
    – researcher
    Jul 23, 2015 at 13:56
  • if [ "$hostname" != "$var" ] works fine :) Thanks a lot. Bests.
    – researcher
    Jul 23, 2015 at 13:57
3

Using an environment variable may be tricky.It might be a matter of the shell you're using: some shells use $HOST, others use $HOSTNAME. I would go with the uname -n option that @grawity mentioned.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .