Skip to content
Advertisement

Bash ssh for loop – env variable issue

When using a bash for loop and ssh’ing to multiple machines the hostname variable is not updated to be the name of the machine I’ve ssh’d into.

What am I missing here?

“A”, “B”, “C” are replaced with names of actual machines and the speech marks removed in the actual execution.

for node in "A" "B" "C" ;
do
    ssh $node "echo $node $HOSTNAME is alive"  ;
done

In the example above $node is correctly outputted but $HOSTNAME is the name of the machine which I SSH from.

Advertisement

Answer

Use single-quotes:

for node in "A" "B" "C" ;
do
    ssh $node 'echo $HOSTNAME is alive';
done

If you need to pass $node,

ssh root@192.168.6.208 'echo ' $node ' $HOSTNAME is alive'

If you use double-quotes, then you are passing the current machine’s HOSTNAME value to a remote machine.

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement