Mark
Mark

Reputation: 4706

Bash: wait for process to exit while tailing log file

In a bash script, I'm waiting on a child process's pid using wait. That child process is writing to a log file. Is there a way in the bash script to tail that log file to std out while at the same time waiting on the process to complete?

Upvotes: 1

Views: 2591

Answers (3)

Rauno Palosaari
Rauno Palosaari

Reputation: 2929

This makes it simpler:

command &
pid=$!
tail --pid=$pid -f /path/to/log

Upvotes: 1

user4815162342
user4815162342

Reputation: 154866

Use the tail command to follow the file while you wait for the command to finish.

command &
cmdpid=$!
tail -f -n +0 logfile &
wait $cmdpid
kill $!

This is in spirit similar to William's solution, but with one important difference: it will correctly print the log file if it takes longer for command to finish than it does for cat to print the file (quite likely, as cat is very fast). The -n +0 option tells tail to print the whole file before it starts following updates.

Upvotes: 4

William Pursell
William Pursell

Reputation: 212218

Run cat in the background:

cmd-that-logs-to-file &
pid=$!
cat file &
wait $pid
kill $!  # Kill the cat

Upvotes: 0

Related Questions