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

命令输出匹配脚本问题:含双指定字符串时误判失败求助

Fixing Your Status Check Script Logic

Let's break down why your original script was failing when both keywords are present, and fix it properly.

The Root of the Problem

Your original condition uses && (logical AND) between two negations:

if [ "$STATUS" != "Ok" ] && [ "$STATUS" != "Non-Critical" ]

When STATUS contains both "Ok" and "Non-Critical" (like "Ok Non-Critical"), both $STATUS != "Ok" and $STATUS != "Non-Critical" are true (since the full string doesn't match either exact value). The && makes the whole condition true, so it triggers the failure message—exactly the opposite of what you want.

Correct Logic Approach

We need to check if the status contains at least one of the allowed keywords ("Ok" or "Non-Critical"). If it does, we pass; if it contains neither, we fail.

Fixed Script Options

Here are two reliable ways to implement this:

Option 1: Using grep (simple and readable)

This uses extended regex to check for either keyword in the status string:

if echo "$STATUS" | grep -qE 'Ok|Non-Critical'; then
    echo "Status check good."
else
    echo "FAILED: STATUS does NOT contain 'Ok' OR 'Non-Critical'"
fi
  • The -q flag makes grep quiet (no output, just exit code)
  • -E enables extended regex for the | (OR) operator

Option 2: Using Bash's native string matching (no external tools)

Bash's [[ construct supports wildcard matching with *, so we can check if the string contains either keyword directly:

if [[ "$STATUS" == *Ok* || "$STATUS" == *Non-Critical* ]]; then
    echo "Status check good."
else
    echo "FAILED: STATUS does NOT contain 'Ok' OR 'Non-Critical'"
fi
  • *Ok* matches any string that has "Ok" anywhere in it
  • || is logical OR, so if either condition is true, the check passes

Verification of All Pass Scenarios

Both scripts will correctly pass for:

  • STATUS="Ok"
  • STATUS="Non-Critical"
  • STATUS="Ok Non-Critical"
  • STATUS="Non-Critical Ok"

And fail for any string that doesn't include either keyword (like "Critical", "Error", or an empty string).

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.13 09:06:28