在Bash脚本中等待服务启动

20

我有一个Bash脚本,在后台启动一些服务。 在此服务成功启动后,它会将“Server is active”打印到标准输出。 我需要等待直到出现此字符串,然后继续执行我的脚本。 我该如何实现这一点?


1
不要那样做。将您的脚本作为服务本身。然后它可能取决于您使用的是 systemd 还是旧的 SysV init.... - Basile Starynkevitch
1
甚至只需在启动时创建一个锁定文件,或检查进程ID,或执行其他操作,没有必要在此处捕获stdout - Reinstate Monica Please
4个回答

16

我会这样做。

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

echo Continue

-m1参数告诉grep(1)在第一次匹配后退出。

我使用下面的"服务"验证了我的答案:

#! /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

如果您将echo Continue替换为 echo Continue; sleep 1; ls /tmp/server-msg.txt ,您将看到ls:无法访问/tmp/server-output.txt:没有那个文件或目录,这证明“继续”操作在输出服务器已激活后立即触发。


7

使用grep -q命令。选项-q可以让grep静默执行,当文本出现时立即退出。

以下命令会在后台启动./some-service并阻塞,直到"Server is active"在标准输出中出现。

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

1
这太棒了!我也做过类似这样的事情:/opt/mssql/bin/sqlservr > /root/sqlservr.out &,然后 tail -f /root/sqlservr.out | grep -q "SQL Server is now ready" - Anu Shibin Joseph Raj

5
为了读取 service 应用程序的服务状态:
$ /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

这可以通过代码完成:

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

0
你是在问如何将标准错误输出重定向到标准输出吗?
./yourscript.sh  2>&1 |grep "Server is active" && echo "continue executing my script"

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接