0

I tried mimic the solution provided in this answer, which finds and kills a process, and developed the following script which ssh to a list of machines specified in the input arguments and kill the desired process.

for node in "$@"; do
  ssh $node "kill $(ps aux | grep '[s]omeprocess' | awk '{print $2}')"
done

The variable $2 used in the awk '{print $2}' should be the second parameter passed by the grep [s]omeprocess. However, it seems that the second input argument of the whole script is used instead (Am I wrong on this part). Can I know how my awk '{print $2}' can really get the second parameter passed by the previous grep operation? Or, is there a nicer way to find and kill a process across multiple machines? Thank you!

Community
  • 1
  • 1
keelar
  • 5,814
  • 7
  • 40
  • 79

1 Answers1

2

The $(ps ..) and the $2 will be expanded on the client side, not the server side. You should escape them:

ssh $node "kill \$(ps aux | grep '[s]omeprocess' | awk '{print \$2}')"

But instead of grepping through ps, you should just use pkill, as in pkill someprocess.

that other guy
  • 116,971
  • 11
  • 170
  • 194
  • Thank you very much, can I further know where I can find more detail descriptions about `$` parameters and `\$` parameters? – keelar Aug 04 '13 at 03:23
  • Oh oh, I think I got your point. By adding `\`, it will pass the actual dollar sign to the target machine, and the interpretation of the dollar sign variable will then happen in the target machine. Am I right at this part? – keelar Aug 04 '13 at 03:24
  • 1
    Exactly right. If you want to know more about when and how to quote and escape, there's a chapter on that in [The Linux Command Line](http://linuxcommand.org/tlcl.php), a free downloadable ebook. – that other guy Aug 04 '13 at 03:28
  • 2
    +1. @keelar: Please also note, that `ps aux | grep` is never a good idea, except for visually seeing the output. because the text someprocess can be anywhere in the command line. At least try to refine ps command. But better, use `pkill` or `killall` :) – anishsane Aug 04 '13 at 14:54