Alex Alex -4 years ago 135
Linux Question

ssh script commands lost after exiting nested shell

I am executing a script through ssh like this:

ssh $USER@somehost 'bash -s' < ./myscript.sh


inside
myscript.sh
:

echo '1'
sudo -i -u svcacct # use the service account
echo '2'
exit # last working command
echo '3'
exit
echo '4'


Output:

shellA$ 1
shellB$ 2
shellA$


As you can see, the
exit
command, while properly exiting the inner session, prevents the subsequent script commands from running. The ssh connection hangs (Ctrl-C exits). How do I fix this?

Answer Source

A working implementation, emitting 1, 2 and 3, would look like:

echo '1'
sudo -u svcacct -i bash -s <<'EOF-1'
echo '2'
EOF-1
echo '3'             
exit
echo '4'

Note that we're not depending on any program to exit leaving the file descriptor for stdin with any particular content queued-up to be read, but instead are providing the svcacct instance with only a very limited and specific subset of stdin from a distinct heredoc.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download