Bash脚本检查服务是否正在运行[重复]

时间:2022-05-25 00:08:43

This question already has an answer here:

这个问题在这里已有答案:

I have written up the following script

我写了以下脚本

#! /bin/bash
function checkIt()
{
 ps auxw | grep $1 | grep -v grep > /dev/null

 if [ $? != 0 ]
 then
   echo $1"bad";
 else
   echo $1"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。由于连字符,似乎出现了麻烦。如果我只检查“php5”,我会得到预期的结果。我实际上可以逃脱它,因为我没有任何其他开始或包含php5的进程。然而,它变成了一个黑客,有一天会重新抬起它丑陋的脑袋。我非常感谢任何能够告诉我如何获得checktt“php5-fpm”工作的人。

2 个解决方案

#1


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输出。

#2


Add word boundaries and a negative lookahead regex to your grep:

在你的grep中添加单词边界和负向前瞻性正则表达式:

#!/bin/bash
function checkIt()
{
 ps auxw | grep -P '\b'$1'(?!-)\b' >/dev/null
 if [ $? != 0 ]
 then
   echo $1"bad";
 else
   echo $1"good";
 fi;
}

checkIt "nginx"
checkIt "mysql"
checkIt "php5-fpm"

#1


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输出。

#2


Add word boundaries and a negative lookahead regex to your grep:

在你的grep中添加单词边界和负向前瞻性正则表达式:

#!/bin/bash
function checkIt()
{
 ps auxw | grep -P '\b'$1'(?!-)\b' >/dev/null
 if [ $? != 0 ]
 then
   echo $1"bad";
 else
   echo $1"good";
 fi;
}

checkIt "nginx"
checkIt "mysql"
checkIt "php5-fpm"