问题
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-indisown
) - 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).
来源:https://stackoverflow.com/questions/24490769/bash-using-ssh-to-start-a-long-running-remote-command-and-collect-its-pid