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

如何在Bash中检测字符串是否为空/未设置或不匹配指定值?

Fixing Your Bash If Condition

Your current condition has a logical flaw that makes it always evaluate to true. Let's break it down and fix it.

The Problem with Your Original Code

if [[ -z $DEP_FLAVOUR || $DEP_FLAVOUR != "develop" || $DEP_FLAVOUR != "release" ]]; then

Using || (OR) between $DEP_FLAVOUR != "develop" and $DEP_FLAVOUR != "release" means one of these two conditions will always be true:

  • If DEP_FLAVOUR is develop, the third condition (!= "release") is true.
  • If DEP_FLAVOUR is release, the second condition (!= "develop") is true.
  • If it's anything else, both are true.

So the entire if block will run no matter what the variable's value is.

Correct Solutions

Option 1: Fix the Logical Operators

You need to check if the variable is empty OR (it's not develop AND not release). Use && for the two "not equal" checks, and wrap them in parentheses to group the logic:

if [[ -z $DEP_FLAVOUR || ($DEP_FLAVOUR != "develop" && $DEP_FLAVOUR != "release") ]]; then
    # Your code here for invalid/empty values
fi

Option 2: Use a case Statement (More Readable)

For condition checks against multiple allowed values, case is often clearer and easier to maintain:

case "$DEP_FLAVOUR" in
    develop|release)
        # Code to run if value is valid (optional)
        ;;
    *)
        # Code to run if value is empty or invalid
        ;;
esac

Option 3: Regular Expression Match

You can also use Bash's regex matching to check if the variable matches either allowed value, then negate the check:

if [[ -z $DEP_FLAVOUR || ! $DEP_FLAVOUR =~ ^(develop|release)$ ]]; then
    # Your code here for invalid/empty values
fi

Key Notes

  • Always double-check logical operators (|| vs &&) when combining conditions—they're easy to mix up.
  • Quoting variables like "$DEP_FLAVOUR" is a good habit to avoid issues with spaces or special characters, though [[ ]] handles unquoted variables more safely than [ ].

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.18 19:50:43