10

I have some service which produces logs in the file logs.log.

I have some other command which interacts with this service. Let's say it is some foo.sh.

What I need, is to cut and save logs from logs.log exactly during foo.sh running. In other words I need that part of service's logs when it interacts with my foo.sh (so I don't care about foo.sh's logs).

I would expect that this command will do the trick, but it continues reading the file when foo.sh has already finished:

> foo.sh | tail -f logs.log > foo_part.log

Is any nice way to perform this trick?

12

This is made rather straightforward by sending your background processes to, well, the background:

foo.sh &
mypid=$!
tail -f /path/to/logs.log > /path/to/partial.log &
tailpid=$!
wait $mypid
kill -TERM $tailpid

$! captures the PID of the last job sent to run in the background, so we can wait on your script to finish, and then kill the tail process when we no longer need it.

  • 3
    awesome answer, learned something new today – Miguel Mota Apr 27 '18 at 20:03
7

This version can do it too (i think):

( tail -f logs.log >foo_part.log &
foo.sh&
wait $! && kill %1 ) 

Note that %1 will hit the first background process in the subshell

  • Personally, I prefer to capture explicit PIDs rather than use the jobs roster, as an increasingly complex implementation of this might put more than one task in the background and kill %1 may get the wrong target. – DopeGhoti Apr 27 '18 at 20:18
  • 1
    Because that i used the subshell parentheses so %1 will refer to the first job inside the subshell (but i am not so sure about this for all shells). Obvious your solution are more complete and functional for more cases, but i think it can do what the user needs.... Another problem is that my version needs at least the creation of foo_part.log with touch, your version do not. – Luciano Andress Martini Apr 27 '18 at 20:33

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.