1

I'm writing a script that logs into a remote server via SSH and executes some commands, one of which logs into a second remote server (which I can't access locally) via SSH and executes a command. After that nested SSH command, my original SSH command terminates and does't complete the rest of the heredoc. I've simplified the script a bit, but I get the same results:

#!/bin/bash
ssh server1 <<'EOF'
  echo one $HOSTNAME
  ssh server2 'echo two $HOSTNAME'    
  echo three $HOSTNAME
EOF

my output looks like this:

one server1
two server2

I would expect to see three server1 at the end of my output, but it doesn't happen. I'm able to separate these into two SSH commands and get what I need, but I'm curious why this is happening, and is it possible to get what I expect in one shot?

Cyrus
  • 84,225
  • 14
  • 89
  • 153
rigglesbee
  • 108
  • 4

1 Answers1

2

Replace

ssh server2

with

ssh -n server2

to prevent ssh reading from stdin.

Cyrus
  • 84,225
  • 14
  • 89
  • 153
  • That works. I see in the ssh manpage that `-n` redirects stdin from /dev/null, but I'm not sure how that relates to the commands that follow. – rigglesbee Apr 12 '18 at 19:41
  • I'm trying to explain. `ssh server2` gets two commands in your example. The first command is `echo two $HOSTNAME` and the second (`echo three $HOSTNAME`) via stdin. The second is ignored. If you remove first command, ssh executes your second command from stdin (replace `ssh server2 'echo two $HOSTNAME'` with `ssh server2`). – Cyrus Apr 12 '18 at 20:36