我有一个带有命令行界面的 CI 服务器,它允许我远程启动一项工作(jenkins
CI 服务器和jenkins-cli.jar
工具)。
在我开始工作后,我tail -f
记录了日志(抱歉命令混乱):
ssh -t my-jenkins-host.com "tail -f \"/var/lib/jenkins/jobs/$job_name/builds/\`ls -ltr /var/lib/jenkins/jobs/$job_name/builds/ | grep '^l' | tail -n 1|awk '{print \$9}'\`/log\""
Run Code Online (Sandbox Code Playgroud)
作业成功完成后,通常至少 5 分钟后,我在输出中得到以下行:
Finished: SUCCESS
Run Code Online (Sandbox Code Playgroud)
有没有什么好方法可以在这一点上停止拖尾日志?即有像tail_until 'some line' my-file.log
命令吗?
奖励:如果您提供的答案在 SUCCESS 匹配时返回 0,FAILURE 匹配时返回 1,并且您的解决方案适用于 mac,则可以获得额外的积分!(我相信这是基于 bsd 的)
Mic*_*zek 49
您可以通过管道输入tail -f
into sed
,告诉它在看到您正在搜索的行时退出:
tail -f /path/to/file.log | sed '/^Finished: SUCCESS$/ q'
Run Code Online (Sandbox Code Playgroud)
sed
将默认输出它处理的每一行,并在看到该行后退出。tail
当它尝试写入下一行并看到其输出管道损坏时,该进程将停止
tail -f my-file.log | grep -qx "Finished: SUCCESS"
Run Code Online (Sandbox Code Playgroud)
-q
, 意思是安静, 一旦找到匹配就退出
-x
使grep
匹配整行
对于第二部分,请尝试
tail -f my-file.log | grep -m 1 "^Finished: " | grep -q "SUCCESS$"
Run Code Online (Sandbox Code Playgroud)
-m <number>
告诉 grep 在数字匹配后停止
并且grep -q
退出状态只会是0
如果SUCCESS
在行尾找到
如果您想查看所有输出,则不能使用grep -q
,但您仍然可以这样做
tail -f my-file.log | grep -m 1 "^Finished: "
Run Code Online (Sandbox Code Playgroud)
如果FAILURE
出现,除了将退出状态设置为 1 之外,它会执行所有操作。
小智 5
我不喜欢这里的任何答案,所以决定推出我自己的答案。此 bash 脚本符合所有标准,并包括失败时退出 1 的奖励。
#!/bin/bash
while IFS= read -r LOGLINE || [[ -n "$LOGLINE" ]]; do
printf '%s\n' "$LOGLINE"
[[ "${LOGLINE}" == "Finished: SUCCESS" ]] && exit 0
[[ "${LOGLINE}" == "Finished: FAILURE" ]] && exit 1
done < <(timeout 300 tail -f my-file.log)
exit 3
Run Code Online (Sandbox Code Playgroud)
还包括超时功能,这将导致退出代码为 3。 如果您的系统上没有 timeout 命令,请从 Anthony Thyssen 获取 timeout.sh 脚本:
https://antofthy.gitlab.io/software/(搜索“超时:”)
根据下面的评论,我更新了日志打印以停止转义字符扩展并包含标准“读取”的所有功能。有关完整的“阅读”详细信息,请参阅/sf/answers/765065801/。这里不需要 EOF 检查,但为了完整性而包括在内。