I am using bash to start several instances of one python program, like this:

python example.py -id $i

where $i is the id given to the instance. All the processes are started on the same user, and imagine I am unable of keeping track of the process IDs. Would it be possible to kill the specific instance just by the command (with id) that called it? For example something like pkill 'python example.py -id 2 which obviously doesn't work.

  • 4
    Try pkill -f python example.py -id 2. The man page for pkill explains the -f flag (see man pkill). And generally, it's a good idea to quote your variables ("$i" instead of just $i). – roaima Jul 25 '16 at 21:42
  • If the processes are running under the current shell, then the jobs command and then kill %2 or whatnot may be of use, to use the shell job control functionality. – thrig Jul 25 '16 at 22:21

kill $(ps -ef | grep '[s]earch-string' | sed -re 's/[[:blank:]]+/\t/g' | cut -f2)

  1. ps -ef : gets process list with arguments
  2. grep : filters for the record you want the [] is to stop grep finding its self.
  3. sed -re 's/[[:blank:]]+/\t/g' : converts space to a single tab
  4. cut -f2 : extracts the pid field
  • 1
    @roaima's comment may be a simpler answer. – ctrl-alt-delor Jul 25 '16 at 21:48
  • Not really portable: ps: unknown option -- f usage: ps [-AaceHhjkLlmrSTuvwx] [-M core] [-N system] [-O fmt] [-o fmt] [-p pid] [-t tty] [-U username] [-W swap] – Kusalananda Jul 30 '16 at 13:14
  • ps is not very portable, there is one for posix, one for bsd, one for system-v. The Gnu one looks like it tries to be compatible with all. If you want help with ps then you will have to tell us which OS and version of ps. – ctrl-alt-delor Aug 11 '16 at 16:25

Using pkill:

pkill -fx 'python example.py -id 2'

The -f option to pkill makes matching happen against the full command line, not just the process name, and -x forces the pattern to match the full command exactly, not just any substring of it (similarly as with grep -x). You'll need -x to avoid matching command lines that possibly had further digits at the end, like 20 or 203.

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.