How can I run command in bash to kill all python scripts except script called test.py and the grep's pid itself, in case we are using something like ps -ef |grep

I think I can use something like pgrep python to ignore the grep process, but how do I also exclude the test.py script? I know there is an option to do grep -v, is there option to do pgrep -v

Clarification: except grep process- means when we do for example ps -ef |grep test1.pywe get also the grep pid that used to bring this result. I don't want to kill it as this process is no longer exist in the stage that results are shown.

  • pgrep and pkill are perhaps better solutions than the usual ps ... | grep -v grep or ps ... | grep '[s]omething' tricks. – thrig Sep 15 '16 at 15:49
  • What should happen if different test.py scripts are running in parallel, possibly with varying command lines (e.g., test.py -a, test.py -b, etc.)? – Malte Skoruppa Sep 15 '16 at 15:50

You could use something along these lines:

pkill $(pgrep python | grep -xv $(pgrep test.py))

Working from the inside out, this:

  1. gathers the PID for test.py with pgrep test.py
  2. sends that PID to grep -xv which will exclude it (-v; the -x option says to match the entire line (PID)) from the list gathered by:
  3. pgrep python to gather the list of python scripts you want to kill

You may need to tweak the pgrep's to find exactly the python processes that you want, but that's the basic structure. Adjust it to your situation by working again from the inside out:

  1. run pgrep test.py to ensure that it finds exactly the PID that you're expecting. Look into the pgrep -f option to match the full process name to be more sure.

  2. run pgrep python (or similar) to find the "python scripts" that you want to kill off.

  3. put it all together!

  • For me, pgrep myscriptname.py doesn't capture any of the instances of the script. I'm on Ubuntu 14.04. – pir Jul 7 '17 at 8:30

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.