我有以下
>写入stdout的Java进程
>启动Java进程的shell脚本
>另一个执行前一个shell脚本并重定向日志
>我使用tail -f命令查看成功消息的日志文件。
即使我在代码中出现0,我也不能结束tail -f进程。
哪个不让我的脚本完成。有什么其他的方法可以在Bash吗?
代码如下所示。
- function startServer() {
- touch logfile
- startJavaprocess > logfile &
- tail -f logfile | while read line
- do
- if echo $line | grep -q 'Started'; then
- echo 'Server Started'
- exit 0
- fi
- done
- }
这是我能想出的最好的答案
对于read,tail -f logfile |放一个超时读-t 30行
>使用–pid = $$启动尾部,这样当bash进程完成时它将退出。
这将涵盖我可以想到的所有情况(服务器挂起,没有输出,服务器退出,服务器正确启动)。
不要忘记在服务器之前启动你的尾巴。
- tail -n0 -F logfile 2>/dev/null | while read -t 30 line
即使不存在,-F也会读取该文件(出现时开始阅读)。 -n0不会读取文件中的任何内容,因此您可以继续附加到日志文件,而不是每次都覆盖它,并且可以对其进行标准的日志轮换。
编辑:
好的,所以一个比较粗糙的“解决方案”,如果你使用尾巴。有可能更好的解决方案使用别的东西,但尾巴,但我必须把它给你,尾巴让你脱离破碎管相当不错。能够处理SIGPIPE的“三通”可能会更好。主动执行文件系统的Java进程可能会更容易等待。
- function startServer() {
- touch logfile
- # 30 second timeout.
- sleep 30 &
- timerPid=$!
- tail -n0 -F --pid=$timerPid logfile | while read line
- do
- if echo $line | grep -q 'Started'; then
- echo 'Server Started'
- # stop the timer..
- kill $timerPid
- fi
- done &
- startJavaprocess > logfile &
- # wait for the timer to expire (or be killed)
- wait %sleep
- }