bash pgrep 检测重复进程

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19037525/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 08:04:18  来源:igfitidea点击:

pgrep detect duplicate processes

linuxbashgrep

提问by Atomiklan

I am trying to use pgrep to first detect if a process is running and if so, determine if the process has been duplicated (run) accidentally. If so, it should it kill the duplicate processes.

我正在尝试使用 pgrep 首先检测进程是否正在运行,如果是,则确定该进程是否已被意外复制(运行)。如果是这样,它应该杀死重复的进程。

if ! pgrep -f "java" > /dev/null; then
  echo "Yes its running but there may be duplicates"
  < Now check for duplicates here and kill if necessary >
fi

Please help

请帮忙

* UPDATE *

* 更新 *

ps aux:

ps辅助:

debian    2521  3.8  5.4 407212 27524 pts/0    Sl   20:16   0:08 java -cp somefile.jar

Code:

代码:

if [ $(pgrep -f "somefile.jar" | wc -l) -gt 1 ]; then
  kill $(pgrep -f "somefile.jar" | grep -v $(pgrep -o "somefile.jar") | awk '{printf " "}');
fi

Works but throws an error

有效但抛出错误

* UPDATE *

* 更新 *

Here is a direct paste of my code:

这是我的代码的直接粘贴:

if [ $(pgrep -f java | wc -l) -gt 1 ]; then
  echo "kill $(pgrep -f java | grep -v $(pgrep -of java) | sort -n | uniq | awk '{printf " "}')";
fi

回答by iamauser

This should do :

这应该做:

#!/bin/bash

if [ $(pgrep -f java | wc -l) -gt 1 ]; then 
  kill $(pgrep -f java | grep -v $(pgrep -of java) | sort -n | uniq | awk '{printf " "}');
fi

pgrep -owill give you the oldest (most likely the first) java process. You want grep -vthat process and kill others.

pgrep -o将为您提供最旧的(很可能是第一个)java 进程。你想要grep -v这个过程并杀死其他人。

回答by Steve Howard

You're using the return code of pgrep, but the output might be more useful if you need to know how many.

您正在使用 pgrep 的返回码,但如果您需要知道有多少,输出可能会更有用。

HOW_MANY_JAVAS = $(pgrep -f 'java' | wc -l)
if ((HOW_MANY_JAVAS > 1)) ; then
  echo 'too much Java.'
fi

回答by konsolebox

An example:

一个例子:

# Collect pids of all java processes in sorted order.
readarray -t PIDS < <(exec pgrep -f java | sort -n)

# Kill all pids except the first.
[[ ${#PIDS[@]} -gt 1 ]] && kill "${PIDS[@]:2}"