4

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.

3
  • 5
    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). Jul 25, 2016 at 21:42
  • 1
    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, 2016 at 22:21
  • python example.py -id $i | id_$1=$! will save pid of python command into id_$i variable. Later you can kill desired ID process by kill -9 ${id_$1}
    – SHW
    Jan 24, 2022 at 7:25

2 Answers 2

2

Using pkill -fx:

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 (just like with grep -x). You'll need -x to avoid matching command lines that possibly had further digits at the end, like 20 or 203.

-1

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

Note: 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.

3
  • 1
    @roaima's comment may be a simpler answer. Jul 25, 2016 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, 2016 at 13:14
  • 1
    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. Aug 11, 2016 at 16:25

You must log in to answer this question.

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