Velvet Star Monitor

Standout celebrity highlights with iconic style.

updates

Wait until service starts in bash-script

Writer Matthew Barrera

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?

2

4 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.

Use grep -q. The -q option makes grep quiet, and it will exit immediately when the text appears.

The command below starts ./some-service in the background, and blocks until "Server is active" appears on stdout.

(./some-service &) | grep -q "Server is active"
1

For me to read service's status as to service app:

$ /sbin/service network status
network.service - Network Connectivity Loaded: loaded (/lib/systemd/system/network.service; enabled) Active: active (exited) since Ср 2014-01-29 22:00:06 MSK; 1 day 15h ago Process: 15491 ExecStart=/etc/rc.d/init.d/network start (code=exited, status=0/SUCCESS)
$ /sbin/service httpd status
httpd.service - SYSV: Apache is a World Wide Web server. It is used to serve HTML files and CGI. Loaded: loaded (/etc/rc.d/init.d/httpd) Active: activating (start) since Пт 2014-01-31 13:59:06 MSK; 930ms ago

and it can be done with the code:

function is_in_activation { activation=$(/sbin/service "$1" status | grep "Active: activation" ) if [ -z "$activation" ]; then true; else false; fi return $?;
}
while is_in_activation network ; do true; done

Are you asking redirect stderr to stdout?

./yourscript.sh 2>&1 |grep "Server is active" && echo "continue executing my script"

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

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