Wait until service starts in bash-script
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
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"
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
.