2016-06-23 64 views
0

我想写一个下面的shell脚本: 我想检查一个服务是否正在运行,如果它正在运行,然后退出1,否则5分钟后它不运行退出 - 1。 类似:Shell脚本+时间依赖关系

while(for 5 minutes) { 
if service running, exit 1 
} 
exit -1 //service is not running even after 5 minutes, so exit -1. 

我可以检查,如果服务正在运行与否,但不能添加时间约束的部分条件。

这就是我试图

if (($(ps -ef | grep -v grep | grep tomcat7 | wc -l) > 0)); 
then 
echo "running" 
else 
echo "NOT running" 
fi 
+0

发布您尝试到现在为止 – syadav

回答

0

您应该使用bashsleep命令。摘自man页面: -

您可以在脚本中提供以等待5分钟并执行操作。

NAME 
     sleep - delay for a specified amount of time 

DESCRIPTION 
     Pause for NUMBER seconds. SUFFIX may be 's' for seconds (the default), 'm' for minutes, 'h' for hours or 'd' for days. Unlike most implementations that require NUMBER be an 
     integer, here NUMBER may be an arbitrary floating point number. Given two or more arguments, pause for the amount of time specified by the sum of their values. 

一种合适的方式到你的解决办法是: - 当ps -ef | grep -v grep | grep "tomcat7"返回该条件通过命令成功错误代码

#!/bin/bash 
maxAttempts=0   
maxCounter=2  # Number of attempts can be controlled by this variable  

while [ "$maxAttempts" -lt "$maxCounter" ]; do 
    if ps -ef | grep -v grep | grep "tomcat7" > /dev/null 
    then 
     echo "tomcat7 service running, " 
     exit 1 
    else 
     maxAttempts=$((maxAttempts+1)) 
     sleep 5m       # The script waits for 5 minutes before exiting with error code '-1' 
    fi 
done 

exit -1 

if条件的作品。 > /dev/null将所有标准输出(stdout,stderr)压制为/dev/null,以便我们只能使用所提供的命令的退出代码。

+0

脚本也应该在5分钟后检查(理想情况下持续5分钟)服务是否正在运行,如果它在5分钟内开始运行,则退出1,如果它在5分钟内不工作,然后退出-1 –

+0

因此,您希望在循环中持续轮询以查看服务是否每5分钟连续运行一次? – Inian

+0

我希望它在一个循环中检查服务是否正在运行,如果它然后退出1.循环运行5分钟。如果它在5分钟内不工作,循环将结束并退出-1。 –