Wait until service starts in bash-script
bash, linux
Solution
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`.
Problem
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?