Bash: Using SSH to start a long-running remote com

2019-08-12 07:18发布

问题:

When I do the following, then I have to press CTRL-c afterwards or the shell acts weird. Left/right arrows keys e.g. doesn't move correctly and the text is messed up.

# read -r pid < <(ssh 10.10.10.46 'sleep 50 & echo $!') ; echo $pid
2135
# Killed by signal 2.
^C
#

I need this for a script, so I'd like to know why CTRL-c is needed and is it possible to work around it?

Update

It looks like it opens an extra Bash shell, and that is the one that needs to be exited.

The command I am actually interesting in is

read -r pid < <(ssh 10.10.10.46 "mbuffer -4 -v 0 -q -I 8023 > /tmp/mtest & echo $!"); echo $pid

回答1:

Try this instead:

read -r pid \
  < <(ssh 10.10.10.46 'nohup mbuffer >/tmp/mtest </dev/null 2>/tmp/mtest.err & echo $!')

Three important changes:

  • Use of nohup (you could also get a similar effect with the bash built-in disown)
  • Redirection of stdin and stderr to files (preventing them from holding handles that connect, eventually, to your terminal).
  • Use of single quotes for the remote command (with double-quotes, expansions happen before ssh is started, so the $! you get is the PID of the most recently started local background process).


标签: linux bash ssh pid