Aditya Jain Aditya Jain - 1 year ago 99
Bash Question

Shell script + time dependency

I wanted to write a shell script for the following:
I want to check if a service is running, if it is running then exit 1, or else after 5 min of it not running, exit -1.
something like:

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

I am able to check the condition that if service is running or not, but not able to add the time constraint part.

This is what i attempted

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

Answer Source

You should use the bash sleep command. An excerpt from the man page:-

You could provide sleep 5m in your script to wait for 5 minutes and do an action.

       sleep - delay for a specified amount of time

       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.

A proper way to your solution would be:-

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
        echo "tomcat7 service running, "
        exit 1
        sleep 5m                           # The script waits for 5 minutes before exiting with error code '-1'

exit -1

The if condition works when the ps -ef | grep -v grep | grep "tomcat7" returns a command success error code for which the condition passes. > /dev/null to suppress all standard outpur(stdout, stderr) to /dev/null so that we can work only with the exit codes of the command provided.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download