0

I want to do something like this:

program='java'
ssh bob@mycomputer "pkill -f $program; echo 'Done!'";

But, it seems like pkill is killing my ssh (I never see Done!). If I replace pkill with something else (say pwd), it works as expected.

pathikrit
  • 32,469
  • 37
  • 142
  • 221
  • 1
    "pkill returns a non-zero exit code which terminates the ssh..." That's not how it works. More likely, pkill is killing the shell instance started by ssh to run your remote command. – Kenster Aug 29 '16 at 19:05
  • You can test the "returns non-zero terminates ssh" theory easily enough with `ssh bob@mycomputer "false; echo Done"` and seeing what happens. – Etan Reisner Aug 29 '16 at 19:12
  • ah ok i was wrong - but my problem still stands. How do I make pkill not drop the ssh ?? – pathikrit Aug 29 '16 at 19:13
  • Even if `pkill` is wrong, your "Done" should get executed. The output will be Done! with error that pkill throws. – divyum Aug 29 '16 at 19:25
  • I updated the question now. – pathikrit Aug 29 '16 at 19:32
  • Try pgrep rather than pkill to hopefully see what is being selected. – Gilbert Aug 29 '16 at 19:42
  • @Gilbert: Nothing is being selected. Its empty – pathikrit Aug 29 '16 at 19:44
  • No help for it but to try a ps -ax type operation to look at the list. I do notice that you use -f, which forces the entire path to match. Kind of dubious about "java" alone. – Gilbert Aug 29 '16 at 19:45

2 Answers2

2

Well seems really a good case here. The -f flag uses the full path of terminal and if its unable to get the process then it kills all the processes it could like pkill -f / which includes ssh. Refer here.

If you try pkill without -f then it works. You can also check ssh verbose (ssh -v) to see what is happening in the background.

Hope it helps.

Community
  • 1
  • 1
divyum
  • 1,286
  • 13
  • 20
1

The chosen answer is wrong, if pkill -f does not find a matching process, it does not kill anything.

The real issue is that when you chain 2+ commands (either with ; or &&), the pkill -f matches with the chained command and kills it. You can verify this behaviour with pgrep:

> ssh bob@mycomputer 'pgrep -f <random_string>'
> ssh bob@mycomputer 'pgrep -f <random_string> ; echo foo'
<chained_command_pid>
foo

Chained command in this case would be $SHELL -c pgrep -f <random_string> ; echo foo (you can add a sleep to the chain and go see it on the remote machine).

Baha2490
  • 11
  • 4