bash 检查进程是否正在运行
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2200203/
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
Check if process is running
提问by chrissygormley
I am trying to check if a process is running. If it is running I want a return value of 'OK' and if not a return value of 'Not OK'. I can only use 'ps' without any other arguments attached (eg. ps -ef) if thats the correct term. The code I have is:
我正在尝试检查进程是否正在运行。如果它正在运行,我想要一个“OK”的返回值,如果不是“Not OK”的返回值。如果那是正确的术语,我只能使用“ps”而不附加任何其他参数(例如 ps -ef)。我的代码是:
if ps | grep file; then echo 'OK'; else echo 'NO'; fi
The problem with this is that it does not search for the exact process and always returns 'OK', I don't want all the information to appear I just want to know if the file exists or not.
这样做的问题是它不会搜索确切的过程并且总是返回“OK”,我不想显示所有信息,我只想知道文件是否存在。
回答by tangens
Your code always returns 'OK', because grep finds itself in the process list ('grep file' contains the word 'file'). A fix would be to do a `grep -e [f]ile' (-e for regular expression), which doesn't find itself.
您的代码总是返回“OK”,因为 grep 在进程列表中找到自己(“grep 文件”包含“文件”一词)。一个解决办法是做一个`grep -e [f]ile'(-e 表示正则表达式),它没有找到自己。
回答by user unknown
Spare grepfor real problems:
饶grep真正的问题:
ps -C file
avoids the problem of using grepaltogether.
grep完全避免使用的问题。
回答by Ignacio Vazquez-Abrams
ps | grep -q '[f]ile'
回答by user3182551
What about "pgrep"?
“pgrep”呢?
$ pgrep -x foo
xxxx
$
where xxxx is the pid of the binary running with the name foo. If foo is not running, then no output.
其中 xxxx 是以名称 foo 运行的二进制文件的 pid。如果 foo 没有运行,则没有输出。
Also:
还:
$ if [[
pgrep -x foo]]; then echo "yes"; else echo "no" ; fi;
$如果[[
pgrep -x foo]]; 然后回声“是”;否则回声“不”;fi;
will print "yes" if foo is running; "no" if not.
如果 foo 正在运行,将打印“是”;“不”如果没有。
see pgrep man page.
请参阅 pgrep 手册页。
回答by mgalgs
When I know the pid I prefer:
当我知道 pid 时,我更喜欢:
[ -d /proc/<pid> ] && echo OK || echo NO
回答by Nischal Hp
if ps | grep file | grep -v grep;
then echo 'ok';
else echo 'no';
grep -v grep makes sure that the result you get is not the grep statement in execution.
grep -v grep 确保您得到的结果不是正在执行的 grep 语句。
回答by Guest67
There is a solution with grep as well:
grep 也有一个解决方案:
if [ "$(ps aux | grep "what you need" | awk '{print }')" == "grep" ]; then
...
elif [ ... ]; then
...
else
...
fi
This works fine in Debian 6, not sure about other distros. '{print $11}'is needed, because the sytem treats grep as a process as well.
这在 Debian 6 中运行良好,不确定其他发行版。'{print $11}'是需要的,因为系统也将 grep 视为一个进程。

