簡體   English   中英

如何在循環中使用tail -f

[英]How to use tail -f in a loop

在bash腳本中,我想顯示我啟動的另一個腳本的輸出,該腳本的執行時間很長,並且包含進度條的輸出重定向到文件。

我想到了在啟動的進程仍在運行時使用tail -f的想法。


假人嘗試:

#!/bin/bash
./worker.sh & # will log in LOG file
while [[ $(kill -0 $!) ]]; do # my implementation of ps does not support the -p option
    tail -f LOG
done
...

由於tail “掛起”,這不起作用。


我使用以下方法找到了解決方法,但是我敢肯定還有另一種更清潔的解決方案:

#!/bin/bash
./worker && pkill tail & # I assumed that worker will always return 0
tail -f LOG
...

所以,我的問題是:在不等待文件完成的情況下顯示正在運行的進程的輸出的最佳方法是什么?

我認為您已經按照正確的方式進行了操作,除了您不應該使用&&之外,因為確實如果./worker失敗, tail進程將永遠不會終止。 相反,您可以使用;分隔命令; ,如:

#!/bin/bash
./worker ; pkill tail &
tail -f LOG

我找到了完美回答這個問題的方法:

tail具有--pid選項:

  --pid=PID with -f, terminate after process ID, PID dies 

因此腳本如下:

#!/bin/bash
./worker.sh & # will log in LOG file
tail -f --pid=$! LOG

不幸的是,至少我的tail(busybox 1.16.1)實現不支持該選項,因此我仍然可以解決。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM