转 聊天服务器
|-转 Docker ERROR: BadValue: security.keyFile is required when authorization is enabled with replica sets
docker_logs="2025-09-26T19:20:00.252754492Z BadValue: security.keyFile is required when authorization is enabled with replica sets 2025-09-26T19:20:00.252809295Z try 'mongod --help' for more information 2025-09-26T19:20:03.737645986Z BadValue: security.keyFile is required when authorization is enabled with replica sets 2025-09-26T19:20:03.737833621Z try 'mongod --help' for more information " if echo "$docker_logs" | grep -qi "BadValue"; then pan duan bu dao
KIMI:
原因
grep 的 -q 选项会把所有输出(包括匹配到的行)都吃掉,只通过退出码告诉你有没有找到。
你后面没检查退出码,所以“判断不到”。
怎么写
1. 直接靠退出码
```bash
if echo "$docker_logs" | grep -qi "BadValue"; then
echo "发现了 BadValue"
fi
```
2. 或者把结果存下来再判断
```bash
hit=$(echo "$docker_logs" | grep -i "BadValue" || true)
if [[ -n $hit ]]; then
echo "发现了 BadValue"
fi
```
3. 纯粹用 Bash 内置,省一次 grep
```bash
if [[ ${docker_logs,,} == *"badvalue"* ]]; then
echo "发现了 BadValue"
fi
```
三种写法都能“判断到”。
bu xing docker_logs=$(docker logs -t --tail 4 "$MONGO_CONTAINER") # 增加日志行数并捕获所有输出
# 更健壮的匹配方式(忽略大小写、特殊字符)
if [[ ${docker_logs,,} == *"badvalue"* ]]; then
log "❌ 检测到 MongoDB 配置错误:"
docker_logs=$(docker logs -t --tail 20 "$MONGO_CONTAINER")
log "$docker_logs" | grep -i "BadValue" | while read -r line; do log "$line"; done
log "====================================================================================="
return 1
else
log "$docker_logs"
log "--------------------------------------------------------------------------------------"
fi
Edit
Copy
Share
你这段脚本逻辑本身没问题,但「还是抓不到 BadValue」通常是因为:
日志里真的还没刷出来
MongoDB 容器刚启动那 1~2 秒可能还没写到 stderr,你 tail 4 行就错过了。
解决:先等 2 s,再一次性多读;或者干脆重试 5 次,每次多读一点。
时间戳把关键字拆断了
2025-09-26T19:20:00.252754492Z BadValue: …
如果 BadValue 出现在行尾,而 tail 截断,就会漏掉。
解决:一次多读(--tail 50),或者干脆去掉 -t 时间戳,再 grep。
大小写没对上
日志里是 BadValue(V 大写),你转成小写再匹配,理论上没问题,但保险起见直接 grep -i 更直观。
docker logs 的 stderr 没捕获
docker logs 默认合并 stdout/stderr,但某些版本或配置可能分开。
解决:加 2>&1 保证都进变量。
给你一份「稳过」的写法
K2
...