Watch a File Being Written in Real Time with tail -f
Watch a file as it grows with tail -f, stop when the writer exits using --pid, and skip the old lines with -n 0. The default prints the last ten lines first.
A job writes a log and you want to watch it live, and to stop watching when the job ends.
seq 1 12 > app.log
( sleep 0.5; for i in a b c; do echo "new $i" >> app.log; sleep 0.5; done ) &
writer=$!
echo "--- last lines, then follow"
tail -n 2 -f --pid="$writer" app.log
echo "--- new lines only"
( sleep 0.5; echo "late line" >> app.log ) &
tail -n 0 -f --pid=$! app.log
echo "tail returned when the writer exited"--- last lines, then follow
11
12
new a
new b
new c
--- new lines only
late line
tail returned when the writer exitedtail -f prints the end of the file and then waits for more, and -n 2 limits the opening lines, here 11 and 12, before it prints the new lines from the writer. --pid makes tail exit once that process has gone, so a script can follow a log for the life of one job without a manual interrupt. -n 0 prints nothing old, which the second part shows with only late line. See tail invocation.
-f follows the file by descriptor, so after the log is rotated by renaming it, tail keeps reading the old file; the manual describes -F as the option that follows the name and retries. --pid is a GNU option. A command whose last step is tail --pid can fail to see its parent's child exit, so end the script with another command.