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
相关产品推荐
相关产品推荐

