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.

3
  • 1
    pkill will be simpler to use than grepping the output from ps. Jun 22, 2016 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. Jun 22, 2016 at 8:09
  • 1
    @Kusalananda According user1700494 's answer -f option did the trick, so you were right! Jun 22, 2016 at 8:34

2 Answers 2

2

Just pkill -f verySpecificChain

1
  • Even much simpler, I did not know that -f option, thanks! Jun 22, 2016 at 8:32
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.

1
  • Indeed that's much simpler to pipe directly, much more relevant than my proposition and that works, thanks! Jun 22, 2016 at 8:17

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .