Search code examples
sshechoeofhostname

How do I parse the remote server name inside echo when executing over ssh


I know the title is a bit confusing but there is no other way.

Script runs and connects to remote server over ssh. This is going to run on 500 servers thatswhy I 'd like to have an output like this on the console.

echo " checking $hostname" or echo " checking ${hostname}" returns nothing. echo " checking $(hostname)" returns the hostname of the local server ironically.

ssh $Server /bin/bash <<EOF
install some software
echo "checking <remote-server-name> after installation"
java -version
groovy -v
jruby -v
EOF

I was just curious if this is doable actually. Thanx in advance.


Solution

  • echo " checking $hostname" or echo " checking ${hostname}" returns nothing.

    That is expected. There is in general no such variable named hostname, so you wouldn't expect a result. There is however a HOSTNAME variable, but that's only half the problem.

    echo " checking $(hostname)" returns the hostname of the local server ironically.

    That's because when you use "here" document, as in

    somecommand << EOF
    ...
    EOF
    

    The contents of the here document are evaluated for variable expansion before the input is fed to your command. This is exactly why the $(hostname) construct is executing the hostname command on your local system.

    You can inhibit the evaluation of the here document by quoting your end marker with single quotes, like this:

    ssh $Server /bin/bash <<'EOF'
    install some software
    echo "checking $HOSTNAME after installation"
    java -version
    groovy -v
    jruby -v
    EOF