Bhavik Joshi Bhavik Joshi - 6 months ago 29
Linux Question

How to fetch a hostname of a remote instance using bash script?

I want the hostname of a remote serve to use in my script.
I am trying this command in script but it is not working.


host= $(ssh -i keylocation ec2-user@ip sudo echo $HOSTNAME)
echo $host

It is giving me the following error:
./ line 3: hostname(The actual host): command not found

Can anyone please help me out.


There are two issues with you code:

  1. The space after the host= is significant, so you should remove it.
  2. The variable $HOSTNAME gets expanded by the local bash.

Try this:

host="$(ssh -i keylocation ec2-user@ip echo '$HOSTNAME')"

or this

host="$(ssh -i keylocation ec2-user@ip hostname)"

I remove the sudo, usually it is not needed to retrieve the hostname.