用于检查服务是否正在运行的 Bash 脚本
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/30093169/
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
Bash script to check if service is running
提问by DroidOS
I have written up the following script
我已经编写了以下脚本
#! /bin/bash
function checkIt()
{
ps auxw | grep | grep -v grep > /dev/null
if [ $? != 0 ]
then
echo "bad";
else
echo "good";
fi;
}
checkIt "nginx";
checkIt "mysql";
checkIt "php5-fpm";
The problem here appears to be with the last check checkIt "php5-fpm"
which consistently returns php5-fpmbad. The trouble appears to arise due to the hyphen. If I do just checkIt "php5"
I get the expected result. I could actually get away with it since I do not have any other process that starts with or contains php5. However, it turns into a hack that will rear up its ugly head one day. I'd be most grateful to anyone who might be able to tell me how to get checkIt "php5-fpm" to work.
这里的问题似乎是最后一次检查checkIt "php5-fpm"
始终返回 php5-fpmbad。问题似乎是由于连字符而出现的。如果我这样做,checkIt "php5"
我会得到预期的结果。我实际上可以逃脱它,因为我没有任何其他进程以 php5 开头或包含 php5。然而,它变成了一种黑客,有一天会抬起它丑陋的脑袋。我将非常感谢任何能够告诉我如何让 checkIt "php5-fpm" 工作的人。
回答by Oleg Mikheev
The normal way to check if service is running or not in *nix is by executing this:
在 *nix 中检查服务是否正在运行的正常方法是执行以下命令:
/etc/init.d/servicename status
e.g.
例如
/etc/init.d/mysqls status
These scripts check status by PID rather than grepping ps output.
这些脚本通过 PID 检查状态而不是 grepping ps 输出。
回答by Juan Diego Godoy Robles
Add word boundaries and a negative lookaheadregex
to your grep
:
为您的:添加单词边界和负面预测:regex
grep
#!/bin/bash
function checkIt()
{
ps auxw | grep -P '\b''(?!-)\b' >/dev/null
if [ $? != 0 ]
then
echo "bad";
else
echo "good";
fi;
}
checkIt "nginx"
checkIt "mysql"
checkIt "php5-fpm"