等到服务以bash-script开始

时间:2014-01-31 08:43:02

标签: linux bash

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

4 个答案:

答案 0 :(得分:12)

我会这样做。

./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: cannot access /tmp/server-output.txt: No such file or directory,证明在Server is active输出后立即触发了“继续”操作。

答案 1 :(得分:2)

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

可以使用代码完成:

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

答案 2 :(得分:0)

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

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

答案 3 :(得分:0)

使用grep -q-q选项可使grep保持安静,并在出现文本时立即退出。

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

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