Ubuntu检查服务状态并启动服务

需求:

  • 检查服务状态
  • 如果服务未启动,则启动服务

实现:

1
2
3
4
5
6
7
8
9
10
function restartService() {
SERVICE=$1
if (( $(ps -ef grep -v grep grep $SERVICE wc -l) > 0 ))
then
echo "service '$SERVICE' is running"
else
echo "start service '$SERVICE'..."
service $SERVICE start
fi
}

用法:

1
restartService mongod

参考:

http://www.akamaras.com/linux/linux-script-to-check-if-a-service-is-running-and-start-it-if-its-stopped/