用于检查服务是否正在运行的Bash脚本

时间:2015-05-07 06:09:30

标签: bash

我已经写了以下脚本

#! /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";

这里的问题似乎是最后一次检查checkIt "php5-fpm",它始终返回php5-fpmbad。由于连字符,似乎出现了麻烦。如果我只做checkIt "php5",我会得到预期的结果。我实际上可以逃脱它,因为我没有任何其他开始或包含php5的进程。然而,它变成了一个黑客,有一天会重新抬起它丑陋的脑袋。我非常感谢能够告诉我如何使用“php5-fpm”工作的人。

2 个答案:

答案 0 :(得分:9)

在* nix中检查服务是否正在运行的正常方法是执行以下操作:

from Tkinter import *
from StringIO import StringIO
from PIL import Image,ImageTk
from urllib import urlopen


url1 = 'https://lh3.googleusercontent.com/-bnh6_0GlqbA/VUKUsl1Pp9I/AAAAAAACGoM/Vx9yu1QGIKQ/s650/Sunset.png'
url2 = 'https://lh3.googleusercontent.com/-_J57qf7Y9yI/VUPaEaMbp9I/AAAAAAACGuM/3f4551Kcd0I/s650/UpsideDawn.png'

window = Tk()

imagebytes = urlopen(url1).read()
imagedata = StringIO(imagebytes)
imagePIL = Image.open(imagedata)
imageready = ImageTk.PhotoImage(imagePIL)

imagelabel = Label(window, image = imageready)
imagelabel.image = imageready

imagelabel.pack()
window.mainloop()

e.g。

/etc/init.d/servicename status

这些脚本通过PID检查状态,而不是grepping ps输出。

答案 1 :(得分:3)

向您的regex添加字词边界和否定预告 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"
相关问题