24

This question already has an answer here:

I need to run tail -f against a log file, but only for specific amount of time, for example 20 seconds, and then exit. What would be an elegant way to achieve this?

marked as duplicate by Jeff Schaller, sebasth, RalfFriedl, YoMismo, DarkHeart Sep 19 '18 at 7:10

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

53

With GNU timeout:

timeout 20 tail -f /path/to/file
  • If the timeout is larger than typical file rotation you might also want to use the follow=name (-F) option of GNU Tail. – eckes Sep 20 '18 at 11:28
18

For completeness sake, without timeout, you can do this:

#!/bin/sh
tail -f /var/log/syslog &
me=$!
trap "kill $me" INT TERM HUP QUIT EXIT
sleep 20

The trap line ensures that when the script or parent shell is terminated (we reach end of script (EXIT), Ctrl-C (INT), sending a SIGTERM via kill, logging out of the shell (HUP), etc) then the tail is killed.

  • I'd need to test it, but I'm pretty sure the last line is not necessary as the shell should trap when exiting? – Olivier Dulac Sep 18 '18 at 14:07
  • 3
    Or you could trap EXIT along with the others. – a CVn Sep 18 '18 at 15:02
  • 1
    @OlivierDulac Only if he trapped EXIT, I believe. – JoL Sep 18 '18 at 15:26
  • Good points all. On testing, a final kill is needed else tail is orphaned off on script exit. Additionally I've modified the script to make trap catch exit and remove the last kill, which looks a more elegant solution. A further shortening could be done by removing the me=$! line and referencing $! in the trap kill directly, but I leave this as an exercise for the consumer :-) – Chris J Sep 19 '18 at 7:35

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