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?
Asked
Active
Viewed 6,517 times
24

Jeff Schaller
- 67,283
- 35
- 116
- 255

Tuyen Pham
- 1,805
2 Answers
56
With GNU timeout:
timeout 20 tail -f /path/to/file

cuonglm
- 153,898
-
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
20
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.

Callie J
- 301
-
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
-
1
-
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 theme=$!
line and referencing$!
in the trap kill directly, but I leave this as an exercise for the consumer :-) – Callie J Sep 19 '18 at 07:35