Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Wait until service starts in bash-script

Tags:

linux

bash

I've a bash-script that starts some service in background. After this service successfully starts it prints "Server is active" to the stdout. I need to wait until this string appears and then continue executing my script. How can I achieve this?

like image 718
Dmitry Stril Avatar asked Jan 31 '14 08:01

Dmitry Stril


People also ask

How do I make bash script wait?

How to Use the Bash Sleep Command. Sleep is a very versatile command with a very simple syntax. It is as easy as typing sleep N . This will pause your script for N seconds, with N being either a positive integer or a floating point number.

Is there a wait command in bash?

The bash wait command is a Shell command that waits for background running processes to complete and returns the exit status. Unlike the sleep command, which waits for a specified time, the wait command waits for all or specific background tasks to finish.

What is $! In bash?

$! bash script parameter is used to reference the process ID of the most recently executed command in background. $$ $$ is used to reference the process ID of bash shell itself.

Does bash do until loop?

In bash for, while, and until are three loop constructs. While each loop differs syntactically and functionally their purpose is to iterate over a block of code when a certain expression is evaluated. Until loop is used to execute a block of code until the expression is evaluated to be false.


1 Answers

I would do in this way.

./server > /tmp/server-log.txt &
sleep 1
while ! grep -m1 'Server is active' < /tmp/server-log.txt; do
    sleep 1
done

echo Continue

Here -m1 tells grep(1) to quit at the first match.

I veryfied my answer with my toy "service" below:

#! /bin/bash

trap "echo 'YOU killed me with SIGPIPE!' 1>&2 " SIGPIPE

rm -f /tmp/server-output.txt
for (( i=0; i<5; ++i )); do
    echo "i==$i"
    sleep 1;
done
echo "Server is active"
for (( ; i<10; ++i )); do
    echo "i==$i"
    sleep 1;
done
echo "Server is shutting down..." > /tmp/server-output.txt

If you replace echo Continue with echo Continue; sleep 1; ls /tmp/server-msg.txt, you will see ls: cannot access /tmp/server-output.txt: No such file or directory which proves the "Continue" action was triggered right after the output of Server is active.

like image 126
nodakai Avatar answered Sep 28 '22 19:09

nodakai