'tail -f' 一段特定的时间

Tuy*_*ham 24 linux tail

我需要tail -f针对日志文件运行,但只能运行特定的时间,例如 20 秒,然后退出。实现这一目标的优雅方式是什么?

cuo*_*glm 55

使用 GNU 超时:

timeout 20 tail -f /path/to/file
Run Code Online (Sandbox Code Playgroud)


Chr*_*s J 19

为了完整起见,没有timeout,您可以这样做:

#!/bin/sh
tail -f /var/log/syslog &
me=$!
trap "kill $me" INT TERM HUP QUIT EXIT
sleep 20
Run Code Online (Sandbox Code Playgroud)

trap行确保当脚本或父 shell 终止时(我们到达脚本结尾 (EXIT)、Ctrl-C (INT)、通过 发送 SIGTERM kill、退出 shell (HUP) 等)然后被终止tail

  • 或者你可以和其他人一起捕获“EXIT”。 (3认同)