我有一个Bash脚本,在后台启动一些服务。 在此服务成功启动后,它会将“Server is active”打印到标准输出。 我需要等待直到出现此字符串,然后继续执行我的脚本。 我该如何实现这一点?
我会这样做。
./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:没有那个文件或目录
,这证明“继续”操作在输出服务器已激活
后立即触发。
使用grep -q
命令。选项-q
可以让grep
静默执行,当文本出现时立即退出。
以下命令会在后台启动./some-service
并阻塞,直到"Server is active"在标准输出中出现。
(./some-service &) | grep -q "Server is active"
/opt/mssql/bin/sqlservr > /root/sqlservr.out &
,然后
tail -f /root/sqlservr.out | grep -q "SQL Server is now ready"
- Anu Shibin Joseph Rajservice
应用程序的服务状态:$ /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
./yourscript.sh 2>&1 |grep "Server is active" && echo "continue executing my script"
systemd
还是旧的 SysV init.... - Basile Starynkevitchstdout
。 - Reinstate Monica Please