繁体   English   中英

等到服务在 bash-script 中启动

[英]Wait until service starts in bash-script

我有一个 bash 脚本,它在后台启动一些服务。 此服务成功启动后,它会将“服务器处于活动状态”打印到标准输出。 我需要等到这个字符串出现,然后继续执行我的脚本。 我怎样才能做到这一点?

我会这样做。

./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 echo Continue; sleep 1; ls /tmp/server-msg.txt echo Continue; sleep 1; ls /tmp/server-msg.txt ,你会看到ls: cannot access /tmp/server-output.txt: No such file or directory证明“Continue”动作在Server is active的输出Server is active后被触发。

使用grep -q -q选项使grep安静,当文本出现时它会立即退出。

下面的命令在后台启动./some-service ,并阻塞直到“服务器处于活动状态”出现在标准输出上。

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

让我阅读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

您是否要求将 stderr 重定向到 stdout?

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM