1

I try to write a function in .bash_profile to define a function for process killing as follows:

function pkill {
                pid = ps -elf|grep python|grep $1|awk -F " " '{print $4}'
                kill -9 pid
}

And what I want to do is using "pkill keyword" to kill the process that pid=[ps -elf|grep python|grep keyword|awk -F " " '{print $4}'],and my code didn't work.How should I write this function?

about kill:
my python process is multithreaded.I've tried kill pid,kill -TERM pid,orkill -INT pid,but still can find it in the processlist.So I used 'kill -9'.

6

3 Answers 3

3
pid=$(ps -elf|grep vim|grep 'screenrc' | awk -F" " '{print $4}')

But you might be able to use pgrep instead:

pid=$(pgrep -f "python .*$1")

or

pids=$(pgrep -d' ' -f "python .*$1")
kill -9 $pids

If you're feeling confident (reckless!):

\pkill -9 -f "python .*$1"
1
  • 1
    Or just pkill -f "python .*$1", as pkill always comes with pgrep. Mar 10, 2010 at 12:58
2

Is there a reason you're listing and then discarding a ton of extra junk?

(I assume you're using GNU ps, but I prefer BSD ps syntax. It's supported by GNU ps, too, because GNU ps supports everything.)

 # as others have noted 'pkill' is an existing command, so let's not clash with its name
 function pypkill {
      pids=$(ps ax -opid= -ocomm= | grep python | grep "$1" | awk -F " " '{print $1}')
      kill -TERM $pids
 }

Breakdown:

  • pids=
    • The sub shell may return more than one PID. This captures all of them
  • $( )
    • a subshell. Commands inside the parentheses will be executed and their output returned in place.
  • ps ax
    • shows all processes on the system (BSD syntax)
  • -opid= -ocomm=
    • tells ps to output two columns: PID and command name, and to ommit the header line
  • kill -TERM $pids
    • Using kill -9 is a last resort. In most cases kill -TERM is what you want, or possibly kill -INT, before resorting to kill -KILL.
0
0

Shouldn't that be more like

  pid=$(ps -elf|grep python|grep $1|awk -F" " '{print $4}')
  kill -9 $pid
4
  • It seems still not work,error info said: bad substitution.:(
    – SpawnST
    Mar 10, 2010 at 9:03
  • @SpawnST: Sorry, I don't have bash here to try it out, I was just guessing. :(
    – Bobby
    Mar 10, 2010 at 9:25
  • 1
    remove the space between -F and " "
    – njd
    Mar 10, 2010 at 12:55
  • 1
    It should be $( ), not ${ }. Mar 10, 2010 at 12:56

You must log in to answer this question.

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