Home  >  Q&A  >  body text

Linux如何根据进程名称的一部分kill掉进程

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

伊谢尔伦伊谢尔伦2724 days ago896

reply all(4)I'll reply

  • 天蓬老师

    天蓬老师2017-04-17 13:44:59

    killall -9 {name}

    reply
    0
  • 怪我咯

    怪我咯2017-04-17 13:44:59

    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

    reply
    0
  • PHP中文网

    PHP中文网2017-04-17 13:44:59

    Let’s try replacing the last pipe with &&

    reply
    0
  • 伊谢尔伦

    伊谢尔伦2017-04-17 13:44:59

    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.

    reply
    0
  • Cancelreply