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?
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.
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.
$! 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.
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.
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With