用于捕获进程ID的Shell脚本,如果存在则将其终止

use*_*811 59 bash shell scripting

我尝试了这个代码,但它无法正常工作

#!/bin/sh

#Find the Process ID for syncapp running instance

PID=`ps -ef | grep syncapp 'awk {print $2}'`

if [[ -z "$PID" ]] then
Kill -9 PID
fi
Run Code Online (Sandbox Code Playgroud)

它在awk附近显示错误.

请给我任何建议.

小智 141

实际上,最简单的方法是传递如下所示的kill参数:

ps -ef | grep your_process_name | grep -v grep | awk '{print $2}' | xargs kill
Run Code Online (Sandbox Code Playgroud)

希望能帮助到你.

  • `grep"your_process"| awk'{print $ 2}'`可以简化为'awk'/ your_process/{print $ 2}'` (4认同)
  • 这会带来在“grep”进程杀死您想要杀死的进程之前杀死“grep”进程的(小)风险。要解决这个问题,请使用 `awk '/[y]our_process/{print $2}' | xargs Kill`​​,但使用 `killall` 更好。 (3认同)
  • 这可能会产生问题,因为ps -ef也可能会给出"grep --color = auto".所以使用`ps -ef | grep"your_process"| awk'{print $ 2}'| grep -v'grep'| xargs杀死` (2认同)

N D*_*auf 14

这对我有好处.

PID=`ps -eaf | grep syncapp | grep -v grep | awk '{print $2}'`
if [[ "" !=  "$PID" ]]; then
  echo "killing $PID"
  kill -9 $PID
fi

  • 只要仅执行该过程的一个实例,此方法就可以正常工作。但是,如果正在运行该流程的两个或多个实例怎么办? (2认同)

gue*_*tli 9

我用这个命令pkill:

NAME
       pgrep, pkill - look up or signal processes based on name and 
       other attributes

SYNOPSIS
       pgrep [options] pattern
       pkill [options] pattern

DESCRIPTION
       pgrep looks through the currently running processes and lists 
       the process IDs which match the selection criteria to stdout.
       All the criteria have to match.  For example,

              $ pgrep -u root sshd

       will only list the processes called sshd AND owned by root.
       On the other hand,

              $ pgrep -u root,daemon

       will list the processes owned by root OR daemon.

       pkill will send the specified signal (by default SIGTERM) 
       to each process instead of listing them on stdout.
Run Code Online (Sandbox Code Playgroud)

如果您的代码通过解释器(java,python,...)运行,那么进程的名称就是解释器的名称.您需要使用参数--full.这与命令名称和参数匹配.


Ama*_*dan 5

你可能想写

`ps -ef | grep syncapp | awk '{print $2}'`
Run Code Online (Sandbox Code Playgroud)

但我会赞同@PaulR 的回答——这killall -9 syncapp是一个更好的选择。