Bash: Using SSH to start a long-running remote command and collect its PID

 ̄綄美尐妖づ 提交于 2020-01-06 01:42:08

问题


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).


来源:https://stackoverflow.com/questions/24490769/bash-using-ssh-to-start-a-long-running-remote-command-and-collect-its-pid

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!