1

I want to kill every processes who match a specific chain. Here is my script, which works pretty well:

echo `ps aux | grep verySpecificChain | grep -v grep | /usr/bin/awk '{ print $2 }'` | xargs kill

Now I want to execute this script from an other user via `su -c:

echo password | su -c "echo `ps aux | grep verySpecificChain | grep -v grep | /usr/bin/awk '{ print $2 }'` | xargs kill" userName;

My problem is that when grep verySpecificChain matches several processes, only the first element is passed to xargs kill:

30598  ==> killed
bash: line 1: 30599: command not found  ==> Not killed
bash: line 2: 30600: command not found  ==> Not killed
bash: line 3: 30606: command not found  ==> Not killed

I really would like to understand why with or without su -c the command behaviour changes?

I'm running GNU bash, version 4.2.53(1)-release (x86_64-redhat-linux-gnu) on Fedora 20.

  • 1
    pkill will be simpler to use than grepping the output from ps. – Kusalananda Jun 22 '16 at 7:55
  • @Kusalananda As far as I've understood, pgrep and pkill use program names only (java, awk, grep...). Assuming my verSpecifyChain is a java parameter then it does not work. – Quentin Morrier Jun 22 '16 at 8:09
  • 1
    @Kusalananda According user1700494 's answer -f option did the trick, so you were right! – Quentin Morrier Jun 22 '16 at 8:34
0

I cannot explain what exactly fails in your example (so I admit it is some kind of voodoo programming on my side), but this is a fix that (almost -- see below*) works in my bash (Debian):

  • get rid of inside echo;
  • escape $2.

Result:

echo password | su -c "ps aux | grep verySpecificChain | grep -v grep | /usr/bin/awk '{ print \$2 }' | xargs kill" userName;

*I wrote "almost works" because Debian won't let me use su in a pipe to echo the password. I must run it without initial echo and type the password interactively. I guess it's not an issue in OP's Fedora.

  • Indeed that's much simpler to pipe directly, much more relevant than my proposition and that works, thanks! – Quentin Morrier Jun 22 '16 at 8:17
2

Just pkill -f verySpecificChain

  • Even much simpler, I did not know that -f option, thanks! – Quentin Morrier Jun 22 '16 at 8:32

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.