如何通过指定进程名称获取进程的PID并将其存储在变量中以进一步使用?

Nid*_*hi 46 unix pid process

通过使用"ucbps"命令,我可以获得所有PID

 $ ucbps

   Userid     PID     CPU %  Mem %  FD Used   Server                  Port
   =========================================================================

   512        5783    2.50   16.30  350       managed1_adrrtwls02     61001
   512        8896    2.70   21.10  393       admin_adrrtwls02        61000
   512        9053    2.70   17.10  351       managed2_adrrtwls02     61002
Run Code Online (Sandbox Code Playgroud)

我想这样做,但不知道该怎么办

  1. variable =按进程名获取进程的pid.
  2. 然后使用此命令kill -9变量.

Ben*_*Ben 87

如果你想基于一个字符串杀死-9(你可能想先尝试杀死),你可以这样做:

ps axf | grep <process name> | grep -v grep | awk '{print "kill -9 " $1}'
Run Code Online (Sandbox Code Playgroud)

这将向您展示您将要杀死的内容(非常非常重要),并sh在执行时将其移除:

ps axf | grep <process name> | grep -v grep | awk '{print "kill -9 " $1}' | sh
Run Code Online (Sandbox Code Playgroud)

  • 我认为这更容易pgrep -f <进程名称> | awk'{print"kill -9"$ 1}'| SH (6认同)
  • 一种避免"grep -v grep"的方法是使用"grep <process nam [e]>",所以它插入字符串并且当第一个grep执行时找不到进程nam [e],如果这是有意义的. (2认同)

XZS*_*XZS 68

pids=$(pgrep <name>)
Run Code Online (Sandbox Code Playgroud)

将为您提供具有给定名称的所有进程的pid.要杀死他们,请使用

kill -9 $pids
Run Code Online (Sandbox Code Playgroud)

避免使用变量并直接终止具有给定名称问题的所有进程

pkill -9 <name>
Run Code Online (Sandbox Code Playgroud)


小智 21

单行......

pgrep -f process_name | xargs kill -9
Run Code Online (Sandbox Code Playgroud)


fla*_*ini 12

另一种可能性是使用pidof它通常伴随大多数发行版.它将使用它的名称返回给定进程的PID.

pidof process_name
Run Code Online (Sandbox Code Playgroud)

这样,您可以将该信息存储在变量中并kill -9在其上执行.

#!/bin/bash
pid=`pidof process_name`
kill -9 $pid
Run Code Online (Sandbox Code Playgroud)