Linux如何根据进程名称的一部分kill掉进程
伊谢尔伦
伊谢尔伦 2017-04-17 13:42:59
0
4
931
ps -ef | grep javadeploy.jar | grep -v grep | awk '{print $2}' | xargs kill

上面这条命令的意思是先通过ps将进程ID得到,然后再kill。但是有一个问题,就是如果这个进程不存在,kill就会出错。如何在这条命令上加个判断,如果存在则运行kill,不存在则不执行kill。

另外试过killall、pkill命令并不能kill。

——————————————分割线——————————————

该问题已经解决,给出解决方法:
1、由于是根据参数的一部分kill,所以直接使用pkill javadeploy.jar不行,但是可以使用pkill -f javadeploy.jar来kill该进程;
2、@小_秦 提供的方法,加上xargs后面--no-run-if-empty,即ps -ef | grep javadeploy.jar | grep -v grep | awk '{print $2}' | xargs --no-run-if-empty kill

伊谢尔伦
伊谢尔伦

小伙看你根骨奇佳,潜力无限,来学PHP伐。

reply all(4)
Peter_Zhu

killall -9 {name}

刘奇

You can use a better shell that automatically prompts you, such as zsh. Enter one or two letters and press the tab key to automatically complete them

Ty80

Let’s try replacing the last pipe with &&

伊谢尔伦

pkill is used to implement kill as part of the process name
pgrep is used for the grep process, directly returning the process number, and does not include pgrep itself

But these two tools have a problem, that is, they do not support matching program parameters.

For your needs, just use xargs honestly.

If you want to make a judgment, Xiao_Qin’s method above is feasible.

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template