简体   繁体   中英

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.

#!/bin/bash

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

It is giving me the following error: ./changeconfig.sh: 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM