TIL: tail log until process exit

:til: :bash:

The --pid flag for tail command can be used to run tail untill particular process exits. It works with -f flag only. Example:

tail --pid <process_id> -f <file.txt>

I have been in situation when particular tool was able to write contents to file only but not stdout. Of course it was possible to provide /dev/stdout instead of file but then piping started to fail with “Permission denied” error. I’ve solved problem in a such way:

  1. Run process in the background & capture pid.
  2. Tail from the file, until previous process exists. Also in the background.
  3. Wait for exit of the 1st process.

This looks like following:

# Tail command is failing if there is no file. Need to ensure the file exists.
echo "" > file.txt

# Run the_tool in the background, write output to file.txt.
(the_tool --output file.txt) &

# Capture pid of process
pid=$!

# Run tail in the background, output can be piped to another tool.
(tail -f --pid "$pid" -n +1 | other_tool ) &

# Wait for process to exit.
wait "$pid"

I think it might be required to wait for tail process too, to make sure all contents are dumped to stdout. But I haven’t faced this problem.