You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Shell脚本运行任务时检测到终端日志含指定字符串如何终止任务

问题原因

你之前用grep检测失败,是因为Python的日志模块默认会将日志输出到**标准错误流(stderr)**而非标准输出流(stdout),仅捕获stdout的grep自然无法匹配到目标内容。

实现方案

你可以使用如下Shell脚本实现需求,会实时捕获目标命令的所有终端输出,匹配到指定字符串后自动终止任务:

#!/bin/bash
# 启动目标命令,合并stderr和stdout,同时保留原始输出
pipenv run python3 run.py --config accounts/user/config.yml 2>&1 | while IFS= read -r line
do
    # 打印原输出到终端,不需要可删除该行
    printf "%s\n" "$line"
    # 匹配目标字符串,命中后终止任务
    if [[ $line == *"INFO | Next session will start at"* ]]; then
        pkill -f "run.py --config accounts/user/config.yml"
        exit 0
    fi
done

补充说明

  • 如果你的系统中不会有重复的run.py执行进程,也可以把pkill -f "run.py --config accounts/user/config.yml"替换为更安全的pkill -P $$ python3,仅杀死当前脚本的子进程
  • 如果你不需要保留原命令的终端输出,删除printf "%s\n" "$line"即可

内容的提问来源于stack exchange,提问作者haashe

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.24 17:45:05