1

I have an app server running in my unix box with process name as abc_test. I have a shell script in which I have to stop my server using /opt/abc/bin/stop. Now sometimes my server doesn't get stopped so I need to check whether my process is still running or not. If it is running then sleep for some seconds and then check again whether process is still running or not. If after 5 minutes process is still running, then I want to exit successfully from the shell script but if the process is not running then exit successfully as well from the shell script.

So I came up with below script but I am not able to understand how to add this 5 minute thing in my below shell script. Does my below script will do exactly as I am thinking? I guess this might be improved as well.

#!/bin/bash

/opt/abc/bin/stop

# Wait for 10 second
sleep 10

# Number of seconds to wait
WAIT_SECONDS=300
# Counter to keep count of how many seconds have passed
count=0

while pgrep abc_test > /dev/null
do
    echo "server is still running."
    # Wait for one second
    sleep 1
    # Increment the second counter
    ((count++))
    # Has the process been killed? If so, exit the loop.
    if ! pgrep abc_test > /dev/null ; then
        break
    fi
    # Have we exceeded $WAIT_SECONDS? If so exit the loop
    if [ $count -gt $WAIT_SECONDS ]; then
        break
    fi  
done
  • 2
    Does my below script will do exactly as I am thinking?. Run it and see? (And then edit with your results, if not). – Michael Homer Dec 17 '15 at 0:51
  • You could use the SECONDS variable to see how many seconds have passed since the script began. – muru Dec 17 '15 at 1:01
3

Assuming /opt/abc/bin/stop doesn't block your script seem to work.
As muru suggested you could skip the $count variable and use the builtin $SECONDS. This would lead to code like this:

/opt/abc/bin/stop
# Wait for 10 second
sleep 10
# Number of seconds to wait
WAIT_SECONDS=300
while pgrep abc_test > /dev/null
do
    echo "server is still running. Seconds: $SECONDS"
    # Wait for one second
    sleep 1
    # Have we exceeded $WAIT_SECONDS? If so exit the loop
    if [ $SECONDS -gt $WAIT_SECONDS ]; then
        break
    fi
done

In case /opt/abc/bin/stop DOES block, just call it in the background like:

/opt/abc/bin/stop &

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.